내 프로그램이 컴파일되지만 포인터로 작업하지 않고 올바르게 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;
}