我正在尝试理解指针。本质上,我试图将一个指针分配给另一个指针,以便获得一个二维动态数组。我可以使用 malloc 来分配 *A 或(假设我已经有一个数组)A[1],但我似乎无法通过首先在 *A 上使用 malloc,然后在 A 上使用另一个 malloc 来创建动态二维数组[1] 扩展数组的该部分。当我尝试访问双分配数组上的 A[1][5] 时,编译器拒绝让我创建程序。我将如何创建这样一个二维分配数组?感谢您的帮助。
#include <stdlib.h>
#include <stdio.h>
int main()
{
int *A;
A=(int *)malloc(sizeof(A)*100);
A[1]=(int *)malloc(sizeof(A[1])*100);
A[1][5]=10;//
printf("%d", (int)sizeof(A[1]));
free(A[1]);
free(A);
}
我怀疑你想要的并不是真正的二维数组,而是一维数组的数组......像这样:
#include <stdio.h>
#include <stdlib.h>
int main()
{
const int NUM_ROWS = 100;
const int NUM_INTS_PER_ROW = 200;
// allocate a dynamic buffer of pointers; each pointer will
// point to a 1D array of integers
int ** rows = (int **) malloc(NUM_ROWS * sizeof(int *));
// for each row, allocate the array of integers
int i;
for (i=0; i<NUM_ROWS; i++) rows[i] = (int *) malloc(NUM_INTS_PER_ROW * sizeof(int));
// Populate the array
int j;
for (i=0; i<NUM_ROWS; i++)
{
for (int j; j<NUM_INTS_PER_ROW; j++) rows[i][j] = 666;
}
// do stuff here...
// Finally, free the data
for (i=0; i<NUM_ROWS; i++) free(rows[i]);
free(rows);
return 0;
}