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

时间:2013-04-15 09:39:16

标签: 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);

当我开始nomtab[0][7](在这种情况下为nbnoeud = 8)时,会出现问题,因为所有值(nomtab[0]nomtab[1],等等)写入的最终值。奇怪的是,检查过后,只有已经访问过的nomtab元素被覆盖了。例如,在第一个循环之后,nomtab[0]= Aaa和其余的等于null;在第二个循环之后,nomtab[0]&amp; nomtab[1] = Baa,其余等于null(见第二张图片)。我想有一个简单明了的解决方案,但这让不知道的事情变得更加无法容忍。

我也尝试过使用strcpy而且不喜欢这样。

有什么想法吗?

输出:

Output:

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

Output with check of array contents after each loop

1 个答案:

答案 0 :(得分:2)

问题出在你的行内

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

相关问题