如何在C中正确分配字符串数组中的指针?

时间:2013-11-24 04:55:33

标签: c string pointers realloc arrays

我在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时,每个元素都是相同的,我已经尝试了&的每个组合。和*我来了。

1 个答案:

答案 0 :(得分:1)

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

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