다음 코드에서는 문자로 단어 문자의 텍스트 파일을로드하려고합니다 다음 해시 테이블 (문자열 배열)각 단어를 저장하려면 노력하고있어하지만 strcpy
전체 단어 저장하지 않는 것 하나의 char
과 나는 이유를 모른다. strcpy
과 strcat
을 잘못 사용하고 있습니까?C에서 strcpy, strcat 사용 충돌?
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include <ctype.h>
# include <stdbool.h>
bool load(const char* dictionary);
#define LENGTH 45
int main (int argc, char* argv[])
{
char* dictionary = argv[1];
load(dictionary);
return 0;
}
bool load(const char* dictionary)
{
int index = 0, words = 0, kk = 0;
int lastl = 0, midl = 0;
char word[LENGTH + 1];
char *wholeword[1001];
FILE* dic = fopen(dictionary, "r");
if (dic == NULL)
{
printf("Could not open %s.\n", dictionary);
return false;
}
for (int c = fgetc(dic); c != EOF; c = fgetc(dic))
{
// allow only alphabetical characters and apostrophes
if (isalpha(c) || (c == '\'' && index > 0))
{
// append character to word
word[index] = c;
index++;
// ignore alphabetical strings too long to be words
if (index > LENGTH)
{
// consume remainder of alphabetical string
while ((c = fgetc(dic)) != EOF && isalpha(c));
// prepare for new word
index = 0;
}
}
// ignore words with numbers (like MS Word can)
else if (isdigit(c))
{
// consume remainder of alphanumeric string
while ((c = fgetc(dic)) != EOF && isalnum(c));
// prepare for new word
index = 0;
}
// we must have found a whole word
else if (index > 0)
{
// terminate current word
word[index] = '\0';
lastl = index - 1;
midl = (index - 1) % 3;
words++;
index = 0;
int hashi = (word[0] + word[lastl]) * (word[midl] + 17) % 1000;
wholeword[hashi] = (char*) malloc(sizeof(char) * (lastl + 2));
strcpy(wholeword[hashi], &word[0]); // ***
for (kk = 1; kk <= lastl + 1; kk++)
{
strcat(wholeword[words], &word[kk]);
}
}
}
fclose(dic);
return true;
}
귀하의 질문에 대한 이해가 어렵습니다. 'strcpy' 함수는 이름에서 알 수 있듯이 문자열을 복사합니다. 'wword' 란 무엇입니까? –
디버거로 코드를 실행 해 보았습니까? – pm100
@DavidSchwartz @DavidSchwartz wword는 여기에서 오타 (편집 됨)로 전체 단어 (문자열 배열)입니다. –