c - 段错误 - C 编程

标签 c arrays string segmentation-fault coredump

这个程序应该读取 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/

相关文章:

c - 迭代C中未初始化的数组

javascript - 基于 "category"属性和 sum "amount"属性减少对象数组

arrays - 如何在 Swift 中合并不同对象的数组

javascript - 异常(exception)情况是固定位置的随机排列数组

c - 卡在空指针和空字符串检查中

c - 为什么要触发两次 SIGINT 才能按预期工作?

python - 使用名为 guppy ( heapy ) 的 Python 工具时 C 代码中的段错误

c - 如何在没有 sleep 的情况下防止 C 中的 linux 软锁定/无响应

c# - 从字符串中提取值

python - 使用正则表达式Python根据模式提取部分字符串