带有struct字段的常量指针数组,可以指向malloc分配的字段?

时间:2011-04-09 18:45:19

标签: c

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)

功能

2 个答案:

答案 0 :(得分:0)

应该是:

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个对象,因此数组[0]指向某个随机地址。

答案 1 :(得分: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;
    }  
}