Difference between `int (* B) [COLSIZE];` and `int * C [ROWSIZE];`?

What is the difference between the following ads?

int (*B)[COLSIZE];
int *C[ROWSIZE];

B = (int (*)[COLSIZE])malloc(ROWSIZE * sizeof(int[COLSIZE]));
for (int i=0; i < ROWSIZE; ++i)
    C[i] = (int *)malloc(COLSIZE * sizeof(int));

      

I understand that both methods are different ways to declare a two dimensional array. But I cannot understand the difference between them. Any graphic explanation would be much appreciated.

+3


source to share


1 answer


B

is a pointer to an array of COLSIZE

int

s, which is used as an array in this context. It is used for a malloc

contiguous array of ROWSIZE

x COLSIZE

ints.

C

is an array of pointers ROWSIZE

to int

. It is used for array malloc ROWSIZE

x COLSIZE

int

s, but the strings are not contiguous - each string is actually a separate 1D array.

In any case, these elements can be addressed as B[i][j]

or C[i][j]

, but the organization of the data under control is different.



When you access B[i][j]

, a simple index computation ("flattened" index i * COLSIZE + j

) is performed .

When accessing, the C[i][j]

pointer is C[i]

first loaded as the base address for the string i

, and then the j

th element of that string is found by adding an offset j

to that base address.

+3


source







All Articles