2016-11-01 6 views
0

다음 코드에서는 문자로 단어 문자의 텍스트 파일을로드하려고합니다 다음 해시 테이블 (문자열 배열)각 단어를 저장하려면 노력하고있어하지만 strcpy 전체 단어 저장하지 않는 것 하나의 char과 나는 이유를 모른다. strcpystrcat을 잘못 사용하고 있습니까?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; 
} 
+0

귀하의 질문에 대한 이해가 어렵습니다. 'strcpy' 함수는 이름에서 알 수 있듯이 문자열을 복사합니다. 'wword' 란 무엇입니까? –

+0

디버거로 코드를 실행 해 보았습니까? – pm100

+0

@DavidSchwartz @DavidSchwartz wword는 여기에서 오타 (편집 됨)로 전체 단어 (문자열 배열)입니다. –

답변

2

strcpy를이 하나의 문자를 복사하지 않습니다, 그것은 복사 옆에 널 ('\0') 바이트까지의 모든 문자. 코드의 시도에 하나의 문자를 복사하려면 :

wholeword[hashi] = &word[0]; 

대신 :

strcpy(wholeword[hashi], &word[0]); 
+0

배열 첨자 앞에 공백을 두지 마십시오. 공백이 매우 가깝고 간격이 너무 길어서는 안됩니다. 예를 들어,'& word [0]'에서 우선 순위는'(& word) [0]'보다는 "& (word [0]')입니다. –

0

예는 strcpystrcat을 오용하는 이러한 기능은 마지막에 (대상 배열에 전체 소스 문자열을 복사 거기에 기존 문자열이 strcat 인 경우).

다음 줄 :

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]); 
    } 
} 

메모리, 복사 그것의 인수 문자열을 할당하고 포인터를 반환

wholeword[hashi] = strdup(word); 

strdup() 단일 호출로 대체 할 수 있습니다.

wholeword[hashi] = malloc(lastl + 2); 
    strcpy(wholeword[hashi], word); 

참고 :

  • 당신이 충돌하지 않고, 당신의 해시 완벽하게 가정 그것은 당신이 그것을 가지고 있지 않다면,이 2 개 개의 라인을 사용, 모든 POSIX 시스템에서 사용할 수 있습니다. 현재 코딩 된대로 충돌이 발생하면 이전 단어가 사전에서 제거되고 해당 메모리가 손실됩니다.
  • 사전 char *wholeword[1001];load 함수의 로컬 변수입니다. 초기화되지 않았으므로 항목이 유효한 포인터인지 여부를 알 수 없습니다. 할당되어야하며 NULL으로 초기화되고 호출자에게 반환됩니다.