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.