我需要保存一个 C 字符串数组。现在我知道 C 字符串只是一个字符数组,所以本质上我想要的是一个二维字符数组。我要存储的字符串也永远不会超过 6 个字符。我的计划是用 50 个“字符串槽”初始化一个 char 数组,然后如果我命中 50 个字符串,则重新分配数组的内存以使其容量加倍。我试过一些简单的东西,比如:
int main() {
char strings[50][6];
strings[0] = "test";
printf("The string is: %s", strings[0]);
return(0);
}
但是,当我去编译它时,我得到了以下错误:
test.c: In function ‘main’: test.c:3: error: incompatible types when assigning to type ‘char[6]’ from type ‘char *’ test.c:4: warning: incompatible implicit declaration of built-in function ‘printf’
谁能给我指出正确的方向?
最佳答案
strncpy(strings[0], "test", 6);
除非你的 C 库有 strlcpy()
。但是,如果您需要改变存储的大小,最好使用 char **
和 malloc()
,realloc()
和 free()
。
关于c - C 中的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3730574/