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!

4

1 回答 1

1

代码是正确的。几点:

所以代码可以重写为:

char** word;
int i;

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

在 C 中,大多数对“字符串”进行操作的函数都要求char数组以空值结尾(printf("%s\n", word[i]);例如)。如果要求缓冲区包含 50 个字符并用作“字符串”,则为空终止符分配一个附加字符:

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

正如eq-所评论的那样,一种不易出错的使用方法sizeof是:

word = calloc(12, sizeof(*word));
于 2012-08-09T16:16:12.557 回答