I am getting an exception when printing a two-dimensional array after initializing it using memset. If I initialize each element and then access it, then there is no error. Please help to figure out the bug in the code.
#include "stdafx.h"
#include "stdlib.h"
int r = 0;
int c = 0;
int **twoDArray() {
int *arr[5];
for (r = 0; r < 5; r++) {
arr[r] = (int*)malloc(2 * sizeof(int));
}
//
for (r = 0; r < 5; r++) {
for (c = 0; c < 2; c++) {
arr[r][c] = 1;
printf("%d \n", arr[r][c]);
}
}
memset(arr, 0, 2 * 5 * sizeof(arr[0][0]));
for (r = 0; r < 5; r++) {
for (c = 0; c < 2; c++) {
printf("%d \n", arr[r][c]); //getting exception here.
}
}
return arr;
}
int main()
{
int **arr;
arr = twoDArray();
for (r = 0; r < 5; r++) {
for (c = 0; c < 2; c++) {
arr[r][c] = 0;
printf("%d \n", arr[r][c]);
}
}
return 0;
}
memsetor not. YourtwoDArrayfunction returns a pointer to a local arrayarr. The latter is automatically destroyed when the function exits. Trying to use the returned result inmaintriggers undefined behavior.