Q:

C Grid using pointers and Malloc

I am Trying to work through some class examples and have gotten stuck on the following:
The array grid should
have length width with each entry representing a column of
cells. Columns that have some occupied cells should be a
malloc'ed character array of length height.
with the given header:
void grid(char **grid, int width, int height)

grid is defined in another file as:
char **grid;

As I have said I have gotten stuck on using malloc, I currently have:
int x;
*grid = malloc(width * sizeof(char));

        for(x = 0; x < width; x++){
            grid[x] = malloc(height * sizeof(char));
        }

Can any one take a look at give me some pointers on the correct way to accomplish "Columns that have some occupied cells should be a
malloc'ed character array of length height.", As I dont understand how the line:

grid[x] = malloc(height *
  sizeof(char));

is equivalent to an array of char's
Thanks

A:

char** grid; is a pointer to pointer.    
grid = malloc( width* sizeof( char* ) ) ;  // Statement 1

for( int i=0; i<height; ++i )
{
    grid[i] = malloc( height ) ; // Statement 2
}

Understand char** -> char* -> char. So first need to reserve for holding addresses amounting to width. By Statement 1, it is achieved. Now each of these index should point to a memory location holding height characters and is achieved by Statement 2.

Diagramatic representation sounds more clear than description. Hope that helps !

A:

In C, an array is a pointer to the first element of the array. So an array is just a memory block, with the array variable pointing onto the first element in this memory block.
malloc() reserves a new memory block of the specified size. To know the size of a type (i.e. number of bytes needed to store one variable of that type), one uses the sizeof operator. Hence a character needs sizeof(char) bytes, and hence height characters need height * sizeof(char).
So with the malloc() call you allocate a memory block to store all the elements of the array, and malloc() returns a pointer onto the first of them.
With C's definition for an array variable (a pointer onto the first element), you can assign the results of malloc(...) to your array variable.

