All
I am writing a very simple C code of dynamic 2D array declaration and initializing it with memset and then printing out the value. My code is something as follows:
float **env;
int i,j,num;
printf("Enter a number : \n");
scanf("%d",&num);
env = (float **)malloc(num*sizeof(float *));
for(i=0;i<num;i++)
{env[i] = (float *)malloc(num*sizeof(float));}
memset(env, 0, sizeof(float)*num*num);
for(i=0;i<num;i++)
{ for (j=0;j<num;j++)
{
printf("%f\t",env[i][j]);
if (j == num -1)
{ printf("\n\n");}
}
}
for(i=0;i<num;i++)
{free(env[i]);
}
free(env);
When I compile the program, there is no compile error or warning, but when I try to print out the values I am not able to print them. Then I debugged the program, and after the memset statement the env 2D variable is showing something like
CXX0030: Error: expression cannot be evaluated, and when I print the values a window appears showing
Unhandled exception at 0x008b1e27 in ***.exe: 0xC0000005: Access violation reading location 0x00000000.
I have tried explicitly initializing the 2D array env to 0 using 2 for loops and it works perfectly and I am also able to print the values, but it doesn’t work when I use memset. It would be very helpful if somebody could help me out. Thank you.
Firstly, the usual advice: stop using type names under
sizeofand stop casting the result ofmalloc. This is what it should’ve looked likeIn general, prefer to write you memory allocations by following this pattern
Secondly, the “array” you create by using this technique is not a classic C-style contiguous 2D array. Instead, you get a “simulated” 2D array assembled from a bunch of completely unrelated 1D arrays. The latter can potentially be scattered randomly in memory. This immediately means that you won’t be able to process your array as a continuous object. Meanwhile your
memsetcall attempts to do just that. You can’t do it this way. In your case you have to zero each 1D sub-array independently, using a cycle.However, instead of allocating your 1D sub-arrays independently, you can allocate them all as a single memory block
If allocated as shown above, you array’s data will be stored in a single continuous memory block, although you still have to understand what you are doing when you are working with that array. For example,
memseting the array data would look as followsor
(which is the same thing).