c - 二维字符数组返回 SEGFAULT

标签 c arrays memory char allocation

我是 C 的初学者,我正在尝试创建一个这样保存的字符串数组:

[1][第一个字符串]

[2][第二串]

[2][三弦] .

.

.

我的实现是这样的:

int counter = 0;
char for_pole[50][50];
strcpy(for_pole[counter][50],"hello");
counter++;
//then i want to print it:
printf("my string: %s", for_pole[0][50]); //prints out first string
printf("my string: %s", for_pole[1][50]); //...and second one

但返回段错误。

我应该使用一些动态内存分配吗? 正如我所说的,我是新手,很抱歉提出了糟糕的问题。

最佳答案

我没有看到你的代码中哪里有第二个字符串。我只看到一个字符串“你好”。

例如你可以这样写

int counter = 0;
char for_pole[50][50];
strcpy(for_pole[counter],"hello");
counter++;
strcpy(for_pole[counter],"world");

//then i want to print it:
printf("my string: %s\n", for_pole[0]); //prints out first string
printf("my string: %s\n", for_pole[1]); //...and second one

至于这个表达

for_pole[counter][50]

然后 1) 索引 50 在数组之外,因为索引的有效范围是 0 - 49 和 2) 它的类型是 char 而不是数组或函数 strcpy 或格式说明符 %s 所需的指向 char 的指针。函数printf

关于c - 二维字符数组返回 SEGFAULT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35004746/

相关文章:

c - 对于数组,为什么 a[5] == 5[a]?

c - 在 C 中提取 double 的最右边 N 位

java - 为什么 Java 在我的 Linux 服务器上使用这么多内存?

c++ - c/c++中指针的内存开销

c - inotify IN_CLOSE_WRITE 仅检测复制到目录的文件

将命令行参数复制到数组中

java - 如何找到重复/重复的数组值并将其显示在输出中?

javascript - JS中带有对象的递归函数

java - 类文件中变量的初始值存储在哪里

ios - 传递 self 并在没有保留周期的闭包中返回它