I used memset() to fill a 2D integer array as below.
int main(){
int** a = calloc( 2, sizeof(int*) );
int i = 0;
for( ; i<2; i++ ){
a[ i ] = calloc( 2, sizeof( int ) );
}
memset( a, 0, 4 * sizeof( int ) ) ;
for( i = 0; i < 2; i++ ){
int j = 0;
for( ; j < 2; j++ ){
printf( "%d ", a[i][j] );
}
printf("\n");
}
}
Output:
Segmentation fault
But if I replace memset( a, 0, 4 * sizeof( int ) ) with:
for( i = 0; i < 2; i++ ){
int j = 0;
for( ; j < 2; j++ ){
a[ i ][ j ] = 0;
}
}
The output is correct:
0 0
0 0
Can anybody tell me why the memset() did not work there?
int (*a)[2] = calloc( 2, sizeof(*a)); /*memset( a, 0, 4 * sizeof( int) );*/`gcc -Wall -Wextra -g) then use a debugger (gdb)