c - (另一个)关于 C 循环和数据结构的问题

标签 c segmentation-fault

我有一个程序(谁的代码在底部可用)可以按照我想要的方式生成数字列表。该程序按原样运行良好,并且完全符合我的要求。我只是不喜欢我写它的方式。如果我改变一件事,它会返回“Segmentation fault”,我也会在底部说到。这是代码:

#include "stdio.h"
#include "stdlib.h"
#define NCH 81

// Generate swap-mode data for bonds for input.conf file

int main() 
{
    int i,j,k;
    int **dat2, *dat;
    //double *dat;

    int ns = 500;

    int nrow = NCH*(ns-1);

    dat = (int*) calloc(nrow, sizeof(int));
    dat2 = (int**) calloc(nrow,sizeof(int*));

    for (i=0; i<nrow; i++) {
        dat2[i] = (int*) calloc(2, sizeof(int));
        for (j=0; j<2; j++)
            dat2[i][j] = 0;
    }

    // Generates the bonds
    k=2;
    for (i=0; i<nrow; i++) {
        k--;
        for (j=0; j<2; j++) {
            dat2[i][j] = k++;
            if ( ((k%501) == 0) ) { 
                k--;
                dat2[i][j] = k++;
                k++;
            }
        }
    }

    FILE *inp2;
    inp2 = fopen("bonds.out", "w");

    for (i=1; i<=nrow; i++)
        fprintf(inp2, "%d %d\n", dat2[i-1][0], dat2[i-1][1]);

    fclose(inp2);

    // Generates the bond ID in the pattern 1 2 3 3 2 1 ... (appropriate for Bond swap!)
    k=1;
    while ( k < nrow ) {
        for (j=0; j<250; j++) {
            dat[k] = (j+1);
            k++;
        }
        for (j=250; j>0; j--) {
            dat[k] = j;
            k++;
        }
    }

    // Scans bonds.out (because just reporting dat2[][] returns segmentation error, not sure why.
    // scans the bonds.out file and stores both values into dm1 and dm2, then reports into 'results.out' file
    int dm1, dm2;

    FILE *inp;
    inp = fopen("input.out", "w");
    inp2 = fopen("bonds.out", "r");

    for (i=1; i<=nrow; i++) {
        fscanf(inp2, "%d %d", &dm1, &dm2);
        fprintf(inp, "%d  %d  %d  %d\n", i, dat[i], dm1, dm2);
    }



    printf("\nDone. All data has been written to \"input.out\"\n");

    fclose(inp2);
    fclose(inp);

    return 0;
}

现在,我不喜欢它首先将 dat2[][] 写入文件然后扫描该文件以获取值的事实。相反,为什么我不能将 dat2[][] 合并到写入 "results.out" 文件的主循环中?如果我这样做,我会得到段错误。为了澄清起见,我的意思是更改代码中的这些行:

for (i=1; i<=nrow; i++) {
    fscanf(inp2, "%d %d", &dm1, &dm2);
    fprintf(inp, "%d  %d  %d  %d\n", i, dat[i], dm1, dm2);
}

对这些:

for (i=1; i<=nrow; i++) {
    fprintf(inp, "%d  %d  %d  %d\n", i, dat[i], dat2[i-1][0], dat2[i-1][1]);
}

我想要一个解释,因为我对 C 还是很陌生。

非常感谢! 阿米特

最佳答案

我想你忘了从 dat 的数组索引中减去 1 ,像这样:

for (i=1; i<=nrow; i++) {
  fscanf(inp2, "%d %d", &dm1, &dm2);
  fprintf(inp, "%d  %d  %d  %d\n", i, dat[i-1], dm1, dm2);
}

这导致段错误的原因是因为您循环直到 i <= nrow , 这将超出 dat 的范围在最后的循环迭代中。

关于c - (另一个)关于 C 循环和数据结构的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4766035/

相关文章:

c - 有没有办法在C中通过超过1层的多态数据结构传递函数指针

c - char 指针 (strdup) 时使用 printf 的段错误

c - 从用户获取字符串并使用 strlen() 查找其长度时出现段错误(核心转储)

c - 返回多维数组的 C 函数的签名

c - 为什么具有整数文字的宏不适用于整数变量?

c - 如何用 C 语言读取和编辑 .txt 文件?

c++ - 当 b 大于 a 中的位数时右移 (a >> b) 的未定义行为?

c++ - 类的二维 vector ,如何引用

c - 为什么这段代码不会导致段错误?

c - C中使用Malloc正确分配二维数组