Originally Posted by
komkamol
You are right that my code is illegal.
This "a" pointer must be allocated with a dynamic memory of 2*sizeof(int [3]).
I had already mentioned that the pointer had been properly memory-allocated so that
I did not show this on my code. And I knew the code I wrote is illegal but I just wanted to tell
you what the member values stored in the "a" variable are, so that someone could give me
a concrete answer to this question with a concrete example.
It is more than just the fact that it is illegal; it does not make sense, either. Well, I presume it does to you. This is slightly better but you still use these mysterious parentheses (in red) in your declaration:
Code:
int (*a)[3] = (int (*) [3])malloc(2*sizeof(int [3]));
I think want you want should look more like this:
Now, if you want to dynamically allocate all of the memory, you are looking at something much more complex:
Code:
#include <stdio.h>
#include <stdlib.h>
#define ROWS 2
#define COLS 3
int main(void) {
int **a = malloc(ROWS*sizeof(int*)),
nums[6] = { 2, 1, 3, 3, 4, 7 },
i, j, c=0;
for (i=0;i<ROWS;i++) {
a[i] = malloc(COLS*sizeof(int));
for (j=0; j<COLS; j++) a[i][j] = nums[c++];
}
printf("%d %d %d\n", a[0][1], a[0][0], a[1][0]);
return 0;
}
Notice it is not necessary to (cast*)malloc in C, and your attempt to include a multiplier in your cast (the green part above) is non-sensical.