【发布时间】:2014-07-10 21:05:55
【问题描述】:
这个程序应该读取 10 个字符串并打印以“ed”结尾的字符串,但是即使它编译,在我输入第一个字符串后我仍然遇到分段错误。我已经尝试了一切,但我无法弄清楚为什么。这是我的代码:
#include <stdio.h>
#include <string.h>
int main(void)
{
//Declaration of array of strings
char *strings[10];
int i = 0;
int len = 0;
//Prompts user to enter 10 strings
printf("Enter 10 strings: \n");
//Loop to read in 10 strings
for( i = 0; i < 10; i++)
{
fgets(strings[i], 100, stdin);
}
//Loop to traverse array of strings and print those ending with 'ed'
printf("The strings that end with ed are:\n");
for( i=0; i < 10; i++)
{
len=strlen(strings[i]);
len=len-1;
if(*strings[len] =='e' && *strings[len-1] =='d')
{
printf("%s", strings[i]);
}
}
return 0;
}//End of function main
【问题讨论】:
-
你的程序将一个未初始化的指针传递给
fgets()。 -
将
char *strings[10]更改为char strings[10][100] -
fgets应该写信到哪里?你还没有分配任何东西。 -
strings[i]在你的循环之前没有被初始化。 -
char *strings[10] 不声明字符串数组。它只是声明了一个指向 char * 的指针数组,并且您不会将这些指针初始化为有效内存。因此,当您尝试访问字符串 [0] 时,您会出现段错误!
标签: c arrays string segmentation-fault coredump