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!
The code is correct. Some points:
calloc()( Do I cast the result of malloc? )sizeof(char)is guaranteed to be 1So code could be rewritten as:
In C, most of the functions that operate on ‘strings’ require the
chararray 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:As commented by eq- a less error prone approach to using
sizeofis: