How to malloc a table in c?

Viewed 189

I'm new to C and am trying to wrap my head around using malloc. I get the importance of using/freeing them but I can't seem to grasp on how to allocate and access them.

Let's say I have a table containing 2 columns of strings with a max width of 10 for column 1 and 8 for column 2. And let's say the number of rows is 3 like the example below. How do I go about creating a malloc to hold the table of values and how do I access it's respective values?

["Turquoise"]["color"  ]
["Tornado"  ]["weather"]
["Triangle" ]["shape"  ]

Any help in illuminating this is much appreciated.

2 Answers

Preferred method:

    char ***table = malloc(rows * sizeof(char **));
    for (size_t i = 0; i < rows; i++)
        table[i] = malloc(cols * sizeof(char *));

It indexes as table[row][col]

but if cols is a compile time constant we can do better and allocate it all at once:

    char *(*table[cols]) = malloc(rows * sizeof(char *[cols]));

Technically there's a way to do this w/o cols being a compile time constant, but I strongly advise against it. Memory isn't expensive enough for it to pay off anymore.

You may do it using malloc like this:

char **array;
int rows,cols;
array=(char **)malloc(rows*sizeof(char *));
for (int i=0;i<row;i++)
{
   array[i]=(char*)malloc(cols*sizeof(char));
}
Related