[英]How to return a pointer to a full array a.k.a int(*)[] to the main function
我的函數目的是在堆上創建一個二維整數數組。 在創建指向整個數組的指針后,我將指向整個數組的指針返回到 void*。 我覺得有更好的返回類型,但我似乎無法獲得寫入語法。
請讓我知道我是否可以做一個更好的返回類型,而不僅僅是一個 void*。
void* create_matrix(int x, int y){
int i, j, count;
int(*matrix)[x] = calloc(y, sizeof *matrix); // a pointer to a full array of size x.
//matrix = address of array
//*matrix = address of first element of array; *(matrix + 1) = address of first element of second array
//**matrix = element that exists at the first element of array; *(*(matrix + 1) + 1) = second element of second array = matrix[1][1]
count = 0;
for(i = 0; i < y; i++){
for(j = 0; j < x; j++){
matrix[i][j] = ++count;
}
}
for(i = 0; i < y; i++){
for(j = 0; j < x; j++){
printf("%d\n", matrix[i][j]);
}
}
return matrix;
}
如果您不從 function返回指針,而是通過引用將其傳遞給 function(即傳遞其地址)並在那里對其進行初始化,則可能會做得更好。 例如
void alloc_matrix(int x, int y, int (**pmat)[x])
{
int (*matrix)[x] = calloc(...);
...;
*pmat = matrix;
}
...
int x = 5;
int y = 6;
int (*matrix)[x]; // important, declare matrix when x is already known
alloc_matrix(x, y, &matrix);
如果需要,您還可以將兩個維度合並到矩陣類型中,即int (*matrix)[x][y]
。 但是你需要寫(*matrix)[i][j]
而不是matrix[i][j]
這有點不方便。 雖然名義上還有一個額外的間接級別,但兩種變體都應該產生完全相同的機器代碼。
您可以返回一個指向未指定大小的數組的指針:
int (*create_matrix(int x, int y))[]
{
...
}
這將與指向 VLA 的指針兼容:
int (*a)[x]=create_matrix(x,y);
數組類型是兼容的,因為兩個地方的大小都不是常數。 這在C 標准的第 6.7.6.2p6 節中指定:
對於要兼容的兩個數組類型,兩者都應具有兼容的元素類型,並且如果兩個大小說明符都存在,並且是 integer 常量表達式,則兩個大小說明符應具有相同的常量值。 如果在要求它們兼容的上下文中使用這兩種數組類型,則如果這兩個大小說明符計算為不相等的值,則為未定義行為
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.