c - C 中的字符串数组

标签 c arrays multidimensional-array cstring

我需要保存一个 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/

相关文章:

c++ - MathGL BoxPlot 的数据格式

将指针强制转换为 long *

java - Android循环遍历一组ImageView并调用一个以ImageView为参数的函数

javascript - 遇到一些 javascript 问题,for 循环。将数字转换为字符串值

c - C 中的二维数组不起作用 - 运行时错误

java - 试图弄清楚如何检查潜在的数组元素是否越界

对 C 中使用指针的宏感到困惑

c - 根据条件将元素添加到两个数组

javascript - 如何通过单击按钮从 react 状态 Hook 数组中删除对象

c++ - 获取和设置二维数组对象值 (C++)