我有一個函式,我在其中動態分配一個陣列,然后稍后使用它,但它在使用之間任意更改:
void func(void){
//allocate two arrays. Tried both malloc and calloc
my_obj* array = calloc(arr_length, sizeof(my_obj*));
my_obj2* array2 = calloc(arr_length_2, sizeof(my_obj2*));
//now I fill the first array with some items
for(int i = 0; i < arr_length; i ){
my_obj o = {1, 2, 3, 4};
array[i] = o;
}
//now I test to make sure I filled the array as planned
for(int i = 0; i < arr_length; i ){
printf("%d\n", array[i].x);
}
//everything prints as planned!
//now I fill the second array, without ever touching the first
for(int i = 0; i < arr_length_2; i ){
my_obj2 o = {1, 2};
array2[i] = o;
}
//now I print the first array again. Instead of the contexts I expect,
//it is full of random data, seemingly completely unrelated to either its
//previous contents or the contents of the second array!
for(int i = 0; i < arr_length; i ){
printf("%d\n", array[i].x);
}
}
正如代碼注釋中所提到的,我的陣列似乎在我從未接觸過它的情況下神奇地發生了變化。是否有可能導致此問題的錯誤?值得注意的是,我在運行 Ubuntu 的 VirtualBox VM 上運行我的代碼。我沒有收到任何型別的錯誤訊息。我已經三重檢查過我真的沒有觸及兩個列印例程之間的第一個陣列。
uj5u.com熱心網友回復:
sizeof(my_obj*) 是指標大小
my_obj* array = calloc(arr_length, sizeof(my_obj*));
my_obj2* array2 = calloc(arr_length_2, sizeof(my_obj2*));
在這里,您試圖訪問您尚未分配的記憶體:
...
array[i] = o;
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/359876.html
上一篇:AddPoint(x,y)使用C
下一篇:在單行上宣告來自普通變數的雙指標
