In which of these steps memory is allocated while trying to allocate 2D array of 20x10
step 1: int (*p)[10];
step 2: p = malloc( 20 * sizeof(*p) );
Do all the memory(20 x 10 x 4 bytes) are allocated in step 2 or some amount of memory is allocated in step 1 also?
Step 1 creates a pointer as an automatic variable. The type pointed to is array-of-10-int
.
Step 2 allocates memory for 20 such arrays (print out sizeof(*p)
to see how big each array is -- the allocated block is 20 times that), and assigns a pointer to that block of memory to p
.
So, p
now points to the first element of an array of 20 arrays-of-10-int
.
If it helps understand, the code is equivalent to:
typedef int my_array[10];
my_array *p = malloc(20 * sizeof(my_array));
The second line of that probably looks more like what you're used to with malloc
. You still can (and should) use sizeof(*p)
rather than sizeof(my_array)
, though.
malloc
is very simple -- it takes a number, and it allocates that many bytes. It doesn't care what type the memory is for. So when in doubt how much memory you're allocating, you can always simply print that number (or look at it in your debugger).