c - 发出写入字符串数组的问题

标签 c arrays string strcpy

由于遇到了稍微复杂的代码部分的问题,我已经删除了它,但错误仍然存​​在。能否粗略看一下并指出我的错误?

//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);

当我通过 [7] 打印 nomtab[0] 时出现问题(nbnoeud = 8,在这种情况下),因为所有值(nomtab[0]nomtab[1] 等)都等于写入的最终值。奇怪的是,检查后,只有 nomtab 中已经访问的元素被覆盖。例如,在第一次循环后,nomtab[0]= Aaa,其余等于null;在第二个循环之后,nomtab[0] & nomtab[1] = Baa 其余等于 null(见第二张图片)。我想对此有一个愚蠢的简单解决方案,但这让不知情的人更加无法忍受。

我也尝试过使用 strcpy 但它不喜欢那样。

有什么想法吗?

输出:

Output:

每次循环后检查数组内容输出

Output with check of array contents after each loop

最佳答案

问题出在你的线路上

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() 分配的字符串缓冲区。

关于c - 发出写入字符串数组的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16011975/

相关文章:

C弦构建

python - 什么会影响超过 64 个字符的字符串的 Python 字符串比较性能?

java - 尽管通过 nextInt() 作为整数输入,但仍被接受为字符串

javascript - 如何避免跳过第二个数组中的数组索引?

javascript - 获取对象内数组内对象的属性

php - 将数组混合在一起

python - 根据字符串长度填充列表的空列表

c - if((x=0)) 在 C 语言中是什么意思?

c++ - 混合符号整数数学取决于变量大小

c++ - 为什么我们需要 memset 始终为零?