c - Dynamic memory allocation and sizeof() -


for allocating memory 2 dimensional array dynamically, write this

int **ar = (int **)malloc(row*sizeof(int*)); for(i = 0; < row; i++)       ar[i] = (int*)malloc(col*sizeof(int)); 

i came across code same cannot understand declaration.

double (*buf)[2] = (double (*)[2])malloc(count*sizeof(double [2]));// explain    printf("%d, %d, %d, %d \n",sizeof(double)); printf(" %d",sizeof(buf[0])); printf(" %d", sizeof(buf)); //prints 8, 16, 16, 4 when count 3 

the output of first printf() trivial. please me next two.

double (*buf)[2] = (double (*)[2])malloc(count*sizeof(double [2]));// explain  

this

double (*buf)[2] 

defines buf pointer array of 2 doubles.

this

(double (*)[2])malloc(count*sizeof(double [2])); 

can (and shall) rewritten

malloc(count * sizeof(double [2])); 

the above line allocates memory size of count times "size array of 2 doubles".

this

= 

assigns latter former.

it ends buf pointing array of count * 2 doubles.

access elements this

(*buf)[0][0]; 

note approach creates pointer "linear" array, array elements store in 1 continues block of memory.

whereas approch 1st mention in question creates "scattered" array array each row might located in seperate block of memory.


this

printf("%d, %d, %d, %d \n",sizeof(double)); 

provokes undefined behaviour, 1st (format) parameter printf expects four addtional parameters , being passed one.

the size of double typically 8.

this

printf(" %d",sizeof(buf[0])); 

prints size of first element buf points to. buf points array of 2 doubles, expected print 2 times "size of double" 2 * 8 = 16.

this

printf(" %d", sizeof(buf)); 

prints size of buf. buf defined pointer, size of pointer on printed. typically 4 32bit implementation , 8 64bit implementation.

note: value of count not appear in of sizes printed above, not directly, nor indireclty, in c not possible derive pointer how memory had been allocated it.


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -