c - 写入和读取文件时出现 SIGSEGV 错误

标签 c runtime-error

<分区>

我正在编写代码来读取和写入文本文件。但是当我运行我的代码时,我遇到了 SIGSEGV 运行时错误。我需要帮助找出代码有什么问题。

#include <stdio.h>
#include <stdlib.h>
int main(){
    /*Variable for writing to file */
    char *name[] = {"Raju", "Nayan", "Hanif"};
    char *id[] = {"100", "101", "102"};
    float cgpa[] = {3.50, 5.00, 4.00};
    /*Variable for reading from file*/
    char *getname, *getid;
    float getcgpa;
    int i;
    FILE *fp;
    fp = fopen("f:\\raju.nog", "w"); /*Create new file */
    for(i=0; i<5; i++){
        fprintf(fp, "%-10s%-10s%-1.2f\n", name[i], id[i], cgpa[i]); /*write to file*/
    }
    fclose(fp);
    /*read from file and print to screen*/
    fp = fopen("f:\\raju.nog", "r");
    while(fscanf(fp, "%s %s %f", &getname, &getid, &getcgpa) != EOF){
        printf("%-10s%-10s%-1.2f\n", getname, getid, getcgpa);
    }

    system("PAUSE");
}

最佳答案

数组:

char *name[] = {"Raju", "Nayan", "Hanif"};
char *id[] = {"100", "101", "102"};
float cgpa[] = {3.50, 5.00, 4.00};

声明 3 个元素但是

for(i=0; i<5; i++){
    fprintf(fp, "%-10s%-10s%-1.2f\n", name[i], id[i], cgpa[i]); /*write to file*/
}

试图遍历 5,从而超出数组的边界。

关于c - 写入和读取文件时出现 SIGSEGV 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12427402/

相关文章:

opencv - opencv2 HOG代码中的运行时错误SIGSEV

authentication - Nginx 身份验证请求意外状态 404

c - 使用 C libwebsockets 将音频流保存在文件中

c - += 工作不正常?

c - 为什么下面的 Flex 代码不显示输出?

c++ - 静态变量是全局变量吗?

typescript - 在 TypeScript 中对非类型化数据强制类型化

SQLite:无法以编程方式打开网络文件,即使之前工作过

Python - Ctype.windll.kernel32.CreateThread 参数值

c - 可见性、Fortran 公共(public)变量、共享库的运行时加载