
-----------------------------------
HazySmoke)345
Sun Oct 31, 2010 10:12 am

A question about 2D arrays
-----------------------------------
So, to the best of my understanding, there are two TYPES of 2D arrays.

[code]// Type 1
int a[3][4]; 

// Type 2
int **b = (int **) malloc (3 * sizeof(int *));
for (i = 0; i < 3; ++i)
    b[i] = (int *) malloc (4 * sizeof(int));

//How to access array elements
a[1][1] = 74;
b[1][1] = 74;
[/code]

In this case, a is an array of array, all of the 12 elements are stored in a continous chunk. But b is an array of pointers, all the rows are stored in different places. If I want, I can even make the rows to have different lengths. We access the 2D arrays the same way, but how they are laid out in memory is a little different.

Here's my first question. Can I create the Type 1 2D array dynamically, using malloc? I think the answer is yes, but someone please confirm that I'm doing this right:

[code]int (*c)[4] = (int (*)[4]) malloc (3 * sizeof(int [4]));

c[1][1] = 74;
[/code]

Also, why doesn't this give compile errors?

[code]#include 
int foo(int (*a)[]) {}
int main(){
    int a[3][4];
    int (*c)[4] = (int (*)[4]) malloc (3 * sizeof(int [4]));
	
    foo(a); //