2017-12-24 12 views
-4

names 배열에 얼마나 많은 이름이 있는지 알고 싶습니다. sizeof(names)/sizeof(names[0])이 정답을 제공합니다. 하지만 문제는 단지 char *names[];을 선언 할 수 없다는 것입니다. 컴파일러가 나에게이 같은 오류를 준다. "이름의 저장을 알 수 없다". 이 오류를 피하려면이 코드를 char *names[] = {"somename", "somename2"};처럼 선언해야합니다. 그러나 문제는 감속 후에 문자열을 할당 할 수 없다는 것입니다. 나는 어떤 조건들 후에 문자열을 할당하고 나의 문제는 그 조건들 후에 내가 가진 많은 문자열들입니다.문자열 배열에 몇 개의 요소가 있습니까?

내보기.

char *names[]; 
char word[10]; 
int i = 0; 
while (fscanf(word, sizeof(word), fp)>0) { 

    // Think hello increase every time loop returns. 
    // such as "hello1", and the 2nd time "hello2" 
    if(strcmp(word, "hello1") == 0) 
    names[i] = word; 
    } 
    printf("size: %d\n", sizeof(names)/sizeof(names[0])); 
+2

그런 다음'malloc'을 사용하여 동적으로 스토리지를 할당하십시오. –

+0

아무것도 명확하지 않습니다 (* 나에게 *). 당신이 시도한 것을 보여줄 수 있습니까? – coderredoc

+0

@OliverCharlesworth 어떻게'malloc'을 사용할 수 있습니까? –

답변

0

어레이 사이즈는 어레이가 생성되면 고정 이다. 그것은 바꿀 수 없습니다. fp 두 번 읽을 수


경우, 단어 수를 위해 파일을 한 번 읽어 보시기 바랍니다.

size_t word_count = 0; 
int word_length_max = 0; 

long pos = ftell(fp); // remember file location 
int n = 0; 
while (fscanf(fp, "%*s%n", &n) != EOF && n > 0) { // Use %n to record character count 
    word_count++; 
    if (n > word_length_max) { 
    word_length_max = n; 
    } 
    n = 0; 
} 

지금 코드가 필요한 word[] 배열 크기 및 최대 길이를 알고있다.

char *words[word_count]; 
char word[word_length_max + 1u]; // buffer size needed to read in the words 

fseek(fp, pos, SEEK_SET); // go back 
for (size_t i=0; i<word_count; i++) { 
    if (fscanf(fp, "%s", word) != 1) { 
    Handle_UnexpectedError(); // 2nd pass should have same acceptable results 
    } 
    words[i] = strdup(word); // allocate a duplicate 
} 

words[]으로 끝나면 할당 된 메모리를 확보하십시오.

.... 
for (size_t i=0; i<word_count; i++) { 
    free(words[i]); 
} 

더 나은 코드는 오류 ftell(), fseek(), malloc()의 반환 값을 확인하고 fscanf(fp, "%s", word)을 제한 할 것입니다.