这个程序应该读取 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
最佳答案
您尚未为string
元素分配内存。为其分配内存。
for(int i = 0; i < 10; i++)
strings[i] = malloc(100);
最后不要忘记使用free
释放分配的内存。
for(int i = 0; i < 10; i++)
free(string[i]);
关于c - 段错误 - C 编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24686277/