【发布时间】:2013-04-15 09:39:16
【问题描述】:
在一段稍微复杂的代码中遇到了问题,我已经删除了它,但错误仍然存在。您能否粗略地看一下并指出我的错误?
//before this, nbnoeud is defined and graphe is a stream that reads from a .txt file
double* xtab = (double *) calloc(nbnoeud, sizeof(double));
double* ytab = (double *) calloc(nbnoeud, sizeof(double));
char** nomtab = (char **) calloc(nbnoeud, 100*sizeof(char));
double x, y; char nom[100]; int numero=0, scancheck;
int a;
for(a=0; a<nbnoeud; a++){
scancheck = fscanf(graphe, "%d %lf %lf %[^\n]", &numero, &x, &y, nom);
if(scancheck = 4) printf("Read item %d; \t Scancheck: %d; \t %s - (%lf, %lf). \n", numero, scancheck, nom, x, y);
xtab[a] = x;
ytab[a] = y;
nomtab[a] = nom; I imagine it's something to do with compatibility of this but to my eyes it all checks out
/*int b; //this section just illustrates that only the previously accessed elements are being overwritten. See code2.png
for(b=0; b<=nbnoeud; b++){
printf("%s \n", nomtab[b]);
}*/
}
for(a=0; a<nbnoeud; a++){
printf("Read item %d; \t \t \t %s - (%lf, %lf). \n", a, nomtab[a], xtab[a], ytab[a]);
}
exit(1);
当我打印nomtab[0] 到[7](在本例中为nbnoeud = 8)时出现问题,因为所有值(nomtab[0]、nomtab[1] 等)都等于最终值被写了。奇怪的是,经过检查,只有 nomtab 的已访问元素被覆盖。例如,在第一个循环之后,nomtab[0]= Aaa,其余等于null;在第二个循环之后,nomtab[0] & nomtab[1] = Baa 其余等于 null(见第二张图片)。我想这有一个愚蠢的简单解决方案,但这使得不知道更加难以忍受。
我也尝试过使用strcpy,但它不喜欢那样。
有什么想法吗?
输出:
每次循环后检查数组内容的输出
【问题讨论】:
-
strcpy 应该可以工作。在使用 strcpy 之前,您是否为 nomtab[a] 分配了内存?