正確分配多維數組這個問題的目的是提供一個關于如何在C中動態正確分配多維數組的參考。這是一個經常被誤解的主題,即使在一些C編程書籍中也很難解釋。因此,即使是經驗豐富的C程序員也很難做到正確。我從編程教師/書籍/教程中了解到,動態分配多維數組的正確方法是使用指針指針。然而,SO上的幾個高代表用戶現在告訴我這是錯誤的和不好的做法。他們說指針到指針不是數組,我實際上并沒有分配數組,而且我的代碼不必要地慢。這就是我教我分配多維數組的方法:#include <stdlib.h>#include <stdio.h>#include <assert.h>int** arr_alloc (size_t x, size_t y){
int** pp = malloc(sizeof(*pp) * x);
assert(pp != NULL);
for(size_t i=0; i<x; i++)
{
pp[i] = malloc(sizeof(**pp) * y);
assert(pp[i] != NULL);
}
return pp;}int** arr_fill (int** pp, size_t x, size_t y){
for(size_t i=0; i<x; i++)
{
for(size_t j=0; j<y; j++)
{
pp[i][j] = (int)j + 1;
}
}
return pp;}void arr_print (int** pp, size_t x, size_t y){
for(size_t i=0; i<x; i++)
{
for(size_t j=0; j<y; j++)
{
printf("%d ", pp[i][j]);
}
printf("\n");
}}void arr_free (int** pp, size_t x, size_t y){
(void) y;
for(size_t i=0; i<x; i++)
{
free(pp[i]);
pp[i] = NULL;
}
free(pp);
pp = NULL;}int main (void){
size_t x = 2;
size_t y = 3;
int** pp;
pp = arr_alloc(x, y);
pp = arr_fill(pp, x, y);
arr_print(pp, x, y);
arr_free(pp, x, y);
return 0;}產量1 2 3
1 2 3這段代碼工作得很好!怎么會錯?
添加回答
舉報
0/150
提交
取消