C中的字符串数组

blc*_*llo 1 c arrays cstring multidimensional-array

我需要保存一个C字符串数组.现在我知道C字符串只是一个字符数组,所以基本上我想要的是一个二维数组的字符.我想要存储的字符串也不会超过6个字符.我的计划是使用50个"字符串槽"初始化一个char数组,然后如果我点击50个字符串,则重新分配该数组的内存以使其容量加倍.我尝试过一些简单的事情:

int main() {
    char strings[50][6];
    strings[0] = "test";
    printf("The string is: %s", strings[0]);
    return(0);
}
Run Code Online (Sandbox Code Playgroud)

但是,当我去编译它时,我收到以下错误:

test.c:在函数'main'中:test.c:3:错误:从类型'char*'test.c中分配类型'char [6]'时出现不兼容的类型:4:警告:不兼容的内置隐式声明在函数'printf'中

谁能指出我正确的方向?

小智 5

strncpy(strings[0], "test", 6);除非你的C库有strlcpy().但是,如果您需要改变存储的大小,最好使用char **with malloc(),realloc()free().

  • `strncpy(strings [0],"testTest",6);`会给你留下未终止的字符串,所以实际上最安全的方法是:`snprintf(strings [0],sizeof(strings [0]) ,"%s","你想要的任何字符串");` (3认同)