【问题标题】:How do I properly assign pointers in string array in C?如何在 C 中正确分配字符串数组中的指针?
【发布时间】:2013-11-24 04:55:32
【问题描述】:

我在 C 语言中遇到了指针问题。我需要将每行的第一个元素放入一个数组中。

重要部分:

char shipname[10];
char **shipTable = NULL;


 while ( fgets( line,100,myfile) != NULL ) {
     sscanf(line, "%s %lf %lf %lf %lf", shipname, &lat, &lng, &dir, &speed);
     shipTable = realloc( shipTable, numofShips*sizeof(char*) );
     shipTable[numofShips-1]=malloc((10)*sizeof(char));
     (shipTable)[numofShips-1] = shipname;
     //char *shipname=malloc((10)*sizeof(char));
     numofShips++;
     }

当我打印出我的 shipTable 时,每个元素都是相同的,我尝试了我想出的 & 和 * 的每种组合。

【问题讨论】:

    标签: c string pointers realloc arrays


    【解决方案1】:

    您正在为 shiptTable 的每个元素分配一个指针值 - 即指向 shipname 的第一个元素的指针,其在内存中的位置永远不会改变。您真正想要做的是每次都复制字符串 - 例如strcpy(shiptable[numofShips-1], shipname).

    或者甚至更好,只是在 sscanf 之前分配内存,并使用 shiptable[numofShips-1] 作为 sscanf 中的参数,而不是 shipname。

    【讨论】:

    • 我 10 分钟前刚试过,感谢您快速准确的回答:D
    猜你喜欢
    • 1970-01-01
    • 2020-09-28
    • 2021-06-28
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-08
    • 2017-04-12
    相关资源
    最近更新 更多