0

So my idea:

A 2-D array is an array of arrays. If an array is X by Y, then each X points to an array with length Y. Is that part correct? Is that why also when you want to dynamically allocate an array in C you have to say

array=(type **)malloc(X*sizeof(type *)). 

The type * is to tell the compiler that each array index will be a pointer to another array so it should be sufficiently big enough to hold pointers o array?

Also why is this loop needed?

for(i =0;i<X;i++)
{
array[i]=(type *)malloc(Y*sizeof(type))
}

Is the cast

(type *)

needed because so that each index is a pointer to a 1-D array? But this time in the malloc we can just say (type) instead of (type *) because the index won't be holding pointers any more?

EDIT

Oh..so this is just mimicking a 2-d array by having an each index in an 1-d array point to another 1-d array. Ok. In that case is my logic for why each malloc have that specific argument make sense? The code here is taken from this SO question dynamic allocation/deallocation of 2D & 3D arrays

Community
  • 1
  • 1
  • For starters, that isn't a 2D array. its an 1D array of pointers. A 2D array is declared as `Type arr[N][M];` where N and M are the dimensions you want. A pointer array is often used to mimic this behavior, but they are *not* the same. – WhozCraig Feb 16 '14 at 12:47
  • [Don't cast the return value of `malloc` in C](http://stackoverflow.com/a/605858/440558). – Some programmer dude Feb 16 '14 at 12:47

1 Answers1

1

Your code doesn't involve an actual 2D array. This is a 2D array:

int myArray[X][Y];

It involves no pointers.

Your code involves a pointer to an array of pointers, which isn't the same thing.


Why is this loop needed?

Because otherwise all of the pointers in your array of pointers don't point at any storage.


Is the cast needed?

No.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680