[英]Constant pointer array with struct fields that may point to malloc allocated fields?
int main() {
Employee *array[SIZE]; //Employee is a typedef struct --includes char *name, DATE *dateOfBirth, DATE is also a typedef struct, has 3 int fields month, day, year,`
fillArray(array, &count, fpin1, fpin2);
freeMemory(array, int count);
}
fillArray(Employee *array[], int *count, FILE *fpin1, FILE *fpin2)
char buffer[MAX], buffer2[MAX];
while (fgets(buffer, MAX, fpin1) != NULL && fgets(buffer2, MAX, fpin2) != NULL){
array[*count]->name = (char *) malloc(sizeof(char)*25);
assert(array[*count]->name != NULL);
strncpy(array[*count]->name, buffer, 15);
strncpy(buffer2, temp, 2);
array[*count]->dateOfBirth->day = atoi(temp)
}
代碼可以編譯,但由於分段錯誤而不斷失敗,似乎在我的fgets上失敗了? 還是我的malloc,我在做什么錯? 我真的似乎無法弄清楚。
另外,您將如何釋放此內存
freeMemory(Employee *array[], int count)
功能?
應該:
int main() {
Employee array[SIZE]; //Employee is a typedef struct --includes char *name, DATE *dateOfBirth, DATE is also a typedef struct, has 3 int fields month, day, year,`
fillArray(&array, &count, fpin1, fpin2);
freeMemory(&array, int count);
}
您沒有在任何地方分配Employee
對象,因此array [0]指向某個隨機地址。
Employee* array[SIZE];
這是一個存儲指向Employee
結構的指針的數組。
我想你是說
fillArray(Employee* array[], int* count, FILE *fpin1, FILE *fpin2)
{
char buffer[MAX], buffer2[MAX];
int i = 0;
while ( fgets(buffer, MAX, fpin1) != NULL &&
fgets(buffer2, MAX, fpin2) != NULL )
{
// the array does not hold any valid memory address.
array[i] = malloc( sizeof(Employee) );
assert( array[i] != NULL );
// now on the new employee add some char memory
(array[i])->name = malloc( sizeof(char) * 25 );
assert(array[i]->name != NULL);
strncpy(array[i]->name, buffer, 15);
strncpy(buffer2, temp, 2);
array[i]->dateOfBirth->day = atoi(temp)
++i;
(*count)++;
}
}
除了看起來很奇怪之外,做array[*count]
總是修改相同的索引。 您從未在任何地方修改*count
。
此代碼不會檢查您是否沒有超過傳遞的array
的范圍。
另外:對於freeMemory()
freeMemory(Employee* array[], int count)
{
int i = 0;
while( i < count )
{
free(array[i]);
array[i] = NULL;
++i;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.