사전을 spellingList라는 큰 배열에 저장하려고합니다. fgets() 루프는 제대로 작동하는 것처럼 보이지만 spellingList에 저장된 내용을 검사 할 때 배열의 모든 요소가 zygote (사전의 마지막 단어)임을 나타냅니다.C char ** 배열은 가장 최근에 할당 된 문자열 만 저장합니다.
에 대해 형식 단어의 긴 목록이 포함되어 사전라는 이름의 파일 :
사전
barbecue
barbecue's
barbecued
barbecues
barbecuing
barbed
.
.
.
zwieback's
zygote
zygote's
zygotes
코드
int i = 0;
int j;
char *pos;
/* Open Dictionary */
FILE *dic;
dic = fopen("dictionary", "r");
/* Malloc Storage Array */
char **spellingList;
spellingList = malloc (sizeof(char*) * 100000);
if (spellingList == NULL){ // if malloc fails
printf("%s\n", "Malloc failure");
exit(0);
}
/* load dictionary into array */
while (1){
if (fgets (word, 50, dic) != NULL){
if ((pos=strchr(word, '\n')) != NULL){ // replace ending '\n' with a '\0'
*pos = '\0';
}
printf("%d %s\n", i, word); // looks as expected
spellingList[i] = word;
i++;
}
else {
break;
}
} fclose(dic); // close fd to dictionary
for (j =0; j < 100; j++){ // output
printf("%d %s\n", j, spellingList[j]);
}
출력
.
.
.
90 zygotes
91 zygotes
92 zygotes
93 zygotes
94 zygotes
95 zygotes
96 zygotes
97 zygotes
98 zygotes
99 zygotes
'단어'가 배열이라고 가정합니다. 그런 다음'spellinglist' 포인트에있는 모든 포인터를 * 같은 배열로 만듭니다. –
같은 포인터 ('word')를 반복해서 저장하고 있습니다. – Ryan
'char **'는 ** 배열이 아닙니다 **! 포인터는 배열이 될 수 없습니다. – Olaf