2012-03-13 99 views
1

這是擴展結構數組的正確方法嗎?擴展結構數組

typedef struct { int x,y,z;} student_record; 

int main(){ 

student_record data_record[30];  // create array of 30 student_records 
num_of_new_records = 5; 

data_record = realloc(data_record,(sizeof(data_record) + (sizeof(student_record)*num_of_new_records))); 

// do I now have an array of 35 student_records??? 

回答

4

否 - 您不能分配給數組。你的代碼甚至不會編譯 - 你試過嗎?

如果你想realloc()你需要有使用malloc()(或其親屬之一):

student_record *data_record = malloc(sizeof(student_record) * 30); 

你可能不應該的realloc()返回值分配回原來的變量,無論是。如果由於某種原因失敗,則會丟失原始指針並泄漏該內存。

+0

那麼我應該使用什麼方法?創建一個更大的新臨時數組並複製,然後malloc()第一個到我想要的大小並再次複製回來? – 2012-03-13 21:54:54

+0

如果你想使用'realloc()',不要使用數組。使用指針和'malloc()'。 – 2012-03-13 21:58:02

1

你應該遵循調用初始大小的模式,然後在必要時使用realloc。重新分配的安全做法需要包括將初始值分配給返回到臨時變量,並在驗證沒有錯誤後覆蓋第一個值。像這樣:

student_record *data_record = malloc(sizeof(student_record) * 30); 
student_record *tmp; 

// need larger size 
if ((tmp = realloc(data_record, new_size)) == NULL) 
    perror(); //possibly exit as well since you're out of memory 
else 
    data_record = tmp; 
1

你只能在堆上的對象(動態分配)使用realloc,因此你必須先malloc。

typedef struct { int x,y,z;} student_record; 

int main() 
{ 
    student_record *data_record = malloc(sizeof(student_record)*30); 
    assert(data_rocord); 
    data_record = realloc(data_record, sizeof(student_record)*35); 
    assert(data_record); 
    free(data_record); 
    exit(EXIT_SUCCESS); 

}