我是 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/