0

I am trying to build a char array of words using calloc.

What I have:

char** word;
word=(char**)calloc(12,sizeof(char*));
for(i=0;i<12;i++){
word[i]=(char*)calloc(50,sizeof(char));
}

Is this correct if I want a char array that has 12 fields each capable of storing 50 characters?

Thanks!

hmjd
  • 120,187
  • 20
  • 207
  • 252
JupiterOrange
  • 339
  • 2
  • 6
  • 18

1 Answers1

1

The code is correct. Some points:

So code could be rewritten as:

char** word;
int i;

word = calloc(12, sizeof(char*));
for (i = 0; i < 12; i++)
    word[i] = calloc(50, 1);

In C, most of the functions that operate on 'strings' require the char array to be null terminated (printf("%s\n", word[i]); for example). If it is required that the buffers holds 50 characters and be used as 'strings' then allocate an additional character for the null terminator:

word[i] = calloc(51, 1);

As commented by eq- a less error prone approach to using sizeof is:

word = calloc(12, sizeof(*word));
Community
  • 1
  • 1
hmjd
  • 120,187
  • 20
  • 207
  • 252
  • + Using `sizeof *ptr_variable` lessens the probability of erring with `sizeof`. – eq- Aug 09 '12 at 16:17