[英]How do I properly assign pointers in string array in C?
我用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的每個元素都相同時,我嘗試了&和*的每種組合。
您正在為shiptTable的每個元素分配一個指針值,即指向shipname的第一個元素的指針,該元素在內存中的位置永遠不變。 您實際要做的是每次都復制字符串-例如strcpy(shiptable[numofShips-1], shipname)
。
甚至更好的是,只需在sscanf之前分配內存,並使用shiptable [numofShips-1]作為sscanf中的參數,而不是shipname。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.