【发布时间】:2011-01-22 03:43:37
【问题描述】:
我有一个程序(谁的代码在底部),它按照我想要的方式生成一个数字列表。该程序按原样运行良好,并且完全符合我的要求。我只是不喜欢我写它的方式。如果我改变一件事,它会返回“分段错误”,我也会在底部说。代码如下:
#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 还是很陌生。
非常感谢! 阿米特
【问题讨论】:
-
我的朋友有很多代码。
-
我知道。我道歉,真的。我认为您不必阅读所有内容。也许只关注最后一点?
标签: c segmentation-fault