【问题标题】:Issue writing to an array of strings问题写入字符串数组
【发布时间】: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] 分配了内存?

标签: c arrays string strcpy


【解决方案1】:

问题出在你的行内

nomtab[a] = nom;

这会将 nomtab[a] 处的指针设置为指向本地数组 nom。但是在使用 fscanf 读取文件 Input 时,每次循环迭代都会覆盖 nom。如果要存储所有字符串,则应复制 nom 并将其存储。您可以使用strdup(nom) 复制 nom。

顺便说一句,您调用 fscanf 时没有限制写入 nom 的字符数。这是一个坏主意。如果文件中有一行太长,那么你将在 nom 中出现缓冲区溢出,覆盖你的堆栈。

编辑: 这条线看起来很可疑:

char** nomtab = (char **) calloc(nbnoeud, 100*sizeof(char));

我猜,你想要的是一个包含 100 个字符长度的 nbnoeud 字符串的数组。您应该将其更改为

char* nomtab = (char *) calloc(nbnoeud, 100*sizeof(char));
strcpy(nomtab[100*a], nom);

char** nomtab = (char **) calloc(nbnoeud, sizeof(char*));
nomtab[a] = strdup(nom);

在第一种情况下,nomtab 是一个包含所有字符串(字符)的大缓冲区,在第二种情况下,nomtab 是一个指向字符串的指针数组,每个字符串都以其他方式分配。在第二种情况下,您需要注意free() 分配的字符串缓冲区。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-09
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-07
    相关资源
    最近更新 更多