當我嘗試在函式中回傳陣列時,我收到錯誤“警告:從回傳型別不兼容的函式“float *”中回傳“float (*)[3]”。我讀過 C 有回傳陣列的問題,但并不真正理解為什么以及如何解決它。這是我的代碼:
float * buildlocs(int L, int W, int H){
int c = 0, xmin, xmax, x, ymin, ymax, y, h;
unsigned int nX, nY;
L = L/4;
W = W/4;
float cellarray[16][3];
for(nX = 0; nX < 4;nX ) {
for(nY = 0; nY < 4;nY ) {
xmin = 0 L*(nX-1);
xmax = L*nX;
x = xmin rand()*(xmax-xmin);
ymin = 0 W*(nY-1);
ymax = W*nY;
y = ymin rand()*(ymax-ymin);
h = rand()*H;
for(int i = 0; i < 3; i ){
if(i == 0){
cellarray[c][i] = x;
}
if(i == 1){
cellarray[c][i] = y;
}
if(i == 2){
cellarray[c][i] = h;
}
}
c = c 1;
}
}
return cellarray;
}
目標是擁有一個包含 3 個變數的 16 個條目的二維陣列。有人可以幫我修復錯誤嗎?
uj5u.com熱心網友回復:
有兩個問題:
首先,float[16][3]是不是一個float*。其次,float cellArray[16][3]在函式結束時不再存在——它是一個只存在于該函式中的區域變數。當你回傳陣列的地址時,指標將指向不存在的東西——所謂的懸空指標。
為了解決這個問題,你需要或者動態分配的陣列和指標回到這樣的動態分配的陣列(不要忘記free,當你與完成cellArray):
float* cellArray = malloc(sizeof(float)*16*3); // this is one contiguous block of floats, you have to figure out how you want to index into this block, since it's stricly speaking not a two dimensional array.
//...//
return cellArray;
或者,我發現更優雅的是,將指標傳遞給已經存在的陣列:
void buildlocs(float* outLocs, int L, int W, int H); // added parameter to take a float*
//in your function that calls buildlocs:
float[16][3] cellArray;
buildlocs(&cellArray[0],L,W,H); // pass allocated array into function, again, this is a pointer, not a two-dimensional array
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/377979.html
上一篇:用戶輸入一個句子(字串)。如何用C中的Enter完成輸入?
下一篇:如何從模式匹配中獲取索引?
