C多维字符数组-赋值使指针中的整数不带强制转换



我创建了一个大的2d字符数组,并希望为其分配字符串。

int i;
char **word;
int start_size = 35000;
word=(char **) malloc(start_size*sizeof(char *));
for(i=0;i<start_size;i++)
    word[i]=(char *) malloc(start_size*sizeof(char));
word[2][2] = "word";

如何分配字符串?请解释为什么此代码不起作用。。。我是低级编程和C的新手,但在高级编程方面经验丰富

您不能在C.中进行字符串赋值

您需要调用一个函数,特别是strcpy()<string.h>中的原型)

#include <string.h>
strcpy(word[2], "word");
word[2][2] = "word";

在上面的语句中,字符串文字"word"被隐式地转换为指向其第一个元素的指针,该元素具有类型char *,而word[2][2]具有类型char。这将尝试为字符分配指针。这解释了您所说的警告信息-

assignment makes integer from pointer without a cast

只能使用字符串文字来初始化字符数组。您需要做的是使用标准函数strcpy来复制字符串文字。此外,不应强制转换malloc的结果。请阅读这篇文章-我是否投射malloc的结果?我建议进行以下更改-

int i;
int start_size = 35000;
// do not cast the result of malloc
char **word = malloc(start_size * sizeof *word);
// check word for NULL in case malloc fails 
// to allocate memory
for(i = 0; i < start_size; i++) {
    // do not cast the result of malloc. Also, the
    // the sizeof(char) is always 1, so you don't need
    // to specify it, just the number of characters 
    word[i] = malloc(start_size);
    // check word[i] for NULL in case malloc
    // malloc fails to allocate memory
}
// copy the string literal "word" to the 
// buffer pointed to by word[2]
strcpy(word[2], "word");

您必须决定是想要字符串列表还是2D字符串数组。


字符串列表如下所示:

char **word;
word = (char**)malloc(start_size*sizeof(char*));
word[2] = "word";

在该示例中,word[2]将是列表中的第三个字符串,而word[2][1]将是第三个串中的第二个字符。


如果你想要一个2D字符串数组,你必须这样做:

int i;
char ***word;
     ^^^ 3 stars
int start_size = 35000;
word = (char***)malloc(start_size*sizeof(char**));
            ^^^ 3 stars                        ^^^ 2 stars
for(i=0;i<start_size;i++)
    word[i] = (char**) malloc(start_size*sizeof(char*));
                   ^^^ 2 stars                     ^^^ 1 star
word[2][2] = "word"; // no it works!

请注意,在C中,malloc之前不需要强制转换。所以这也会起作用:

word = malloc(start_size*sizeof(char**));

最新更新