2013-11-24 3 views
0

나는 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을 인쇄 할 때, 같은 내가 &의 모든 조합을 시도하고 * 난에 와서있다.

답변

1

shiptable의 각 요소에 포인터 값을 할당합니다. 즉, 메모리에서 위치가 변경되지 않는 shipname의 첫 번째 요소에 대한 포인터입니다. 실제로 수행하려는 작업은 매번 문자열을 복사하는 것입니다. strcpy(shiptable[numofShips-1], shipname).

또는 sscanf 앞에 메모리를 할당하고 shipname 대신 sscanf에서 shiptable [numofShips-1]을 인수로 사용하십시오.

+0

방금 ​​전에 10 분이 지났습니다. 빠르고 정확한 답을 주셔서 감사합니다. D – Heksan

관련 문제