0

So I have a program with a struct

typedef struct s_struct {
    int rows;
    int cols;
    char* two_d; //This is supposed to be the 2D array
} *GRID; 

I want to create a struck and dynamically allocate memory to it and then fill the 2D array but I don't know how. Here is what I have for the create(int prows, int pcols) function:

GRID grid = malloc(sizeof(struct s_struct));
grid ->rows = prows;
grid ->cols = pcols;
grid ->two_d = malloc(sizeof(char) * (rows*cols));

I don't understand how this creates a 2D array if it even does and how I can go about filling the array.

code
  • 69
  • 1
  • 9
  • 1
    [This](http://www.geeksforgeeks.org/dynamically-allocate-2d-array-c/) may help. – Axalo Apr 17 '15 at 03:20
  • There are many posts on SO on the subject. Checkout http://stackoverflow.com/search?q=[c]+create+dynamic+2D+array. – R Sahu Apr 17 '15 at 03:22
  • fdo not typedef struct definitions. It clutters the code, leads to misunderstandings, and clutters the compiler name space. Then the tag name 's_struct' is not informative. much better would be 'grid_t. then use 'struct grid_t' in all future references. Note: all caps 'GRID' is (by programing convention) reserved for macro/#define names. – user3629249 Apr 17 '15 at 03:23

1 Answers1

-1

this line:

grid ->two_d = malloc(sizeof(char) * (rows*cols));

allocates a 'continuous in memory' grid/matrix that can be referenced by:

grid[row_offset][cols_offset]

where the 'row_offset' can be 0...(row-1)

where the 'cols_offset' can be 0...(cols-1)

note: 'sizeof(char)' is always 1, 
so including that phrase
in the malloc parameter just clutters the code 
because '(1*something)' is always 'something' 
as the 1 has no effect.

suggest: remove the 'sizeof(char)' from the malloc parameter

user3629249
  • 16,402
  • 1
  • 16
  • 17