【问题标题】:segmentation error in for loop in c [closed]c中for循环中的分段错误[关闭]
【发布时间】:2023-03-07 19:13:01
【问题描述】:

我有一个文本文件,其中包含如下排列的数字:

0.200   1.3300   1.2555
0.201   1.3300   1.2620
0.202   1.3300   1.2685
0.203   1.3300   1.2751
0.204   1.3248   1.2817
.
.
.
.
0.899   0.17380   5.7153
0.900   0.17435   5.7227

这个文本文件有 700 行。我编写了一个 C 程序,它将从另一个名为“fc.txt”的文本文件中读取行号,然后将该特定行的三个不同数字保存到三个不同的文本文件中.程序是:

#include<stdio.h>
int main()
{
    int l, i = 0, j;
    float a[100][100];
    float *p;
    FILE *fp;
    fp = fopen("fc.txt", "r");
    fscanf(fp, "%d", &l);
    fclose(fp);
    fp = fopen("Au.txt", "r");
    for (i = 0; i <= l; i++)
    {
        for (j = 0; j <= 2; j++)
        {
            fscanf(fp, "%f", &a[i][j]);
            if (i == l)
            {
                p = &a[i][j];
                p++;
            }
        }
    }
    fclose(fp);
    fp = fopen("i_ri.txt", "w");
    fprintf(fp, "%f", *(p - 1));
    fclose(fp);
    fp = fopen("r_ri.txt", "w");
    fprintf(fp, "%f", *(p - 2));
    fclose(fp);
    fp = fopen("w.txt", "w");
    fprintf(fp, "%f", *(p - 3));
    fclose(fp);
    return 0;
}

90程序中“fc.txt”中写入的行号运行正常时。但是当行号为 100 时,会显示一条消息

****"* 检测到堆栈破坏 *:**./ri 终止 中止(核心转储)“******

在第 120 行之后显示:

分段错误(核心转储)

但是我需要运行这个程序 700 行。请提出一些解决此问题的方法。

【问题讨论】:

  • 你能正确缩进你的代码吗?您只读取了 6 个值 .... 文件打开是否正常?
  • 您想将 700 个元素写入 100 个元素的数组。怎么可能适合?
  • 请edit 您的问题并显示您期望的每个输出文件的前 2-3 行。还要明确哪个是包含 700 行的文件的名称
  • float a[100][100]; ==> float a[700][3];
  • 你真的不应该存储你不需要的行。而且您只能将 3 个值读取并使用到 100 个数组中。内存浪费巨大,总体速度较慢。

标签: c for-loop segmentation-fault scanf ram


【解决方案1】:

我无法理解你的目的。我猜你想读取特定行的数据。

未经测试的演示:

#include<stdio.h>

int main(int argc, char *argv[])
{
    char *src;
    int nr;
    int i;
    float a[3];
    FILE *fp;

    if (argc != 3)
    {
        printf("Usage: %s <file> <line_number>\n", argv[0]);
        return -1;
    }

    src = argv[1];
    nr = atoi(argv[2]);

    if ((fp = fopen(src, "r")) == NULL)
    {
        printf("Fail to open file %s\n", src);
        return -1;
    }

    for (i = 0; i < nr; i++)
    {
        if (fscanf(fp, "%f %f %f", a, a + 1, a + 2) != 3)
        {
            printf("Unknown format\n");
            return -1;
        }
    }

    fclose(fp);

    // Now float arrays at line nr is stored at a[]
    printf("Your expected float array: \n");
    printf("[1] %f\n[2] %f\n[3] %f\n", a[0], a[1], a[2]);

    // Do your own job with a[]

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-20
    • 2013-08-21
    • 2017-09-13
    • 2015-08-09
    • 1970-01-01
    • 1970-01-01
    • 2020-09-03
    • 1970-01-01
    相关资源
    最近更新 更多