繁体   English   中英

C 多维字符数组 - 赋值从指针生成整数而不进行强制转换

[英]C multidimentional char array - assignment makes integer from pointer without a cast

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

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");

您必须决定是需要字符串列表还是二维字符串数组。


字符串列表的工作方式如下:

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

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


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

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**));
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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM