2013-04-30 3 views
2

내 프로그램이 컴파일되지만 포인터로 작업하지 않고 올바르게 realloc합니다. 다른 예제를 살펴 보았지만 내 프로그램으로 번역 할 수없는 것 같습니다. 프로그램의 요점은 파일에서 단어를 읽고 두 번 이상 나타나면 카운트를 증가시키는 것입니다. 일단 구조체의 배열이 내 기지 (5) 넘어 가면, 나는 공간을 재 할당하고, 배열을 복사 한 다음 다음 단어를 추가하고 싶다.C에서 구조체 배열에 대해 realloc을 사용하려고 시도하는 포인터가 유효하지 않습니다.

도움이 될 것입니다.

holder = realloc(wordArray, sizeof(wordArray) +1); 

참고 man page of realloc()에서이 행 :

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
#define BASE 5 
#define MAX 50 

typedef char *string; 

struct wordCount 
{ 
string word; 
unsigned int count; 
    }; 

int main (void) 
{ 
unsigned int i; 
unsigned int incremented; 
unsigned int j; 
char temp [40]; 
struct wordCount wordArray[BASE]; 
struct wordCount *holder; 
FILE *infile; 

j = 0; 
infile = fopen("input.txt","r"); 
while (fscanf(infile, "%s", temp) == 1) { 
    incremented = 0; 
    for (i = 0; i < j; i++){ 
     if(strcmp(temp,wordArray[i].word) == 0){ 
      wordArray[i].count++; 
      incremented++; 
     } 
    } 
    if (incremented == 0){ 
     if (j<BASE){  
      wordArray[j].word = (char *)malloc((strlen(temp)+1) * 
           sizeof(char)); 
      strcpy(wordArray[j].word,temp); 
      wordArray[j].count = 1; 
      j++; 
     } else { 
      holder = realloc(wordArray, sizeof(wordArray) +1); 
      *wordArray = *holder; 
      wordArray[j].word = (char *)malloc((strlen(temp)+1) * sizeof(char)); 
      strcpy(wordArray[j].word,temp); 
      wordArray[j].count = 1; 
      j++; 
     } 
    } 
} 

fclose(infile); 

/* bring in next file*/ 
/*delete du plicates */ 
/*sort*/ 

for (i = 0; i < j; i++) { 
    printf("%s ", wordArray[i].word); 
    printf("%d\n", wordArray[i].count); 
} 
/* and when done:*/ 
    for(i = 0; i < j; i++){ 
     free(wordArray[i].word); 
} 

return 0; 
} 

답변

3

다음은 잘못된거야 가장 눈에 띄는 장소

무효 * realloc을 (무효 *의 PTR,이 size_t 크기);
...
ptr이 NULL이 아닌 한 malloc(), calloc() 또는 realloc()에 대한 이전 호출에 의해 반환되어야합니다.

귀하의 wordArray는 정적으로 할당 된 배열, 동적으로 malloc()이나 친구를 통해 할당되지 않았습니다.

관련 문제