这是完整的代码。现在一直结冰
typedef struct {
char *name;
} NAME;
将数组设置为空,然后我根据需要添加多少条目来扩展它。
NAME *array = NULL;
int itemCount = 0; // items inserted
int arraySize = 0; // size of array
int arrayCount; //gets size of file.
int found = 0;
int Add(NAME item)
{
if(itemCount == arraySize) {
if (arraySize == 0)
arraySize = 3;
else
arraySize *= 2; // double size of array
//relocate memory
void *tempMemory = realloc(array, (arraySize * sizeof(NAME)));
//error relocating memory
if (!tempMemory)
{
printf("Couldn't relocate the memory \n");
return(-1);
}
array = (NAME*)tempMemory;
}
array[itemCount] = item;
itemCount++;
return itemCount;
}
void printStruct()
{
int i;
for(i = 0; i < arrayCount; i++)
{
printf("%s \n", array[i].name);
}
}
int readFromFile()
{
int checkResult(char[]);
FILE *fp;
fp = fopen("names.txt", "r");
char names[arrayCount];
if (fp == NULL)
{
printf("Cannot access file \n");
}else{
while(!feof(fp))
{
fscanf(fp, "%s", names);
arrayCount++;
checkResult(names);
}
}
fclose(fp);
return 1;
}
int checkResult(char names[]){
NAME tempStruct;
int i;
if(array == NULL)
{
tempStruct.name = malloc((strlen(names) + 1) * sizeof(char));
strcpy(tempStruct.name, names);
tempStruct.count = 1;
}
else
{
for(i = 0; i < arrayCount; i++)
{
if(strncmp(array[i].name, names, arrayCount)==0)
{
printf("MATCH %s", names);
break;
}
}
if(i == arrayCount)
{
tempStruct.name = malloc((strlen(names) + 1) * sizeof(char));
strcpy(tempStruct.name, names);
}
if (Add(tempStruct) == -1)
{
return 1;
}
}
}
主要是我释放内存并调用其他函数
int main(){
void printStruct();
int readFromFile();
readFromFile();
printStruct();
int i;
for (i = 0; i < arrayCount; i++)
{
free(array[i].name);
}
free(array);
return 0;
}