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
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
sizeofoperator. Hence a character needssizeof(char)bytes, and hence height characters needheight * 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.