A question about 2D arrays
Author |
Message |
HazySmoke)345
![](http://i10.photobucket.com/albums/a121/HazySmoke/clubps2.jpg)
|
Posted: Sun Oct 31, 2010 10:12 am Post subject: 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;
|
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;
|
Also, why doesn't this give compile errors?
code: | #include <stdlib.h>
int foo(int (*a)[]) {}
int main(){
int a[3][4];
int (*c)[4] = (int (*)[4]) malloc (3 * sizeof(int [4]));
foo(a); //<-- HERE
foo(c); //<-- AND HERE
free(c);
}
|
Note that I did not specify the column width in foo, You'd think it should be like this
code: | int foo(int (*a)[4]) {}
|
And lastly, what's the real difference between MALLOC and CALLOC? I get the impression that we *should* use malloc for creating single objects and calloc for arrarys, but time and time again I see people creating arrays using malloc. |
|
|
|
|
![](images/spacer.gif) |
Sponsor Sponsor
![Sponsor Sponsor](templates/subSilver/images/ranks/stars_rank5.gif)
|
|
![](images/spacer.gif) |
OneOffDriveByPoster
|
Posted: Wed Nov 03, 2010 4:41 pm Post subject: Re: A question about 2D arrays |
|
|
code: | int (*c)[4] = (int (*)[4]) malloc (3 * sizeof(int [4]));
c[1][1] = 74;
| Yes, that is okay (assuming malloc did not return null). malloc() does not initialize the memory it returns, calloc() sets all bytes to zero. |
|
|
|
|
![](images/spacer.gif) |
|
|