以下是在堆上创建2D数组(或动态分配2D数组)的不同方法。
在以下示例中, 我们考虑了"[R‘作为行数, ‘C‘作为列数, 我们创建了一个2D数组, 其中r = 3, c = 4和以下值
1 2 3 4
5 6 7 8
9 10 11 12
1)使用单个指针:
一种简单的方法是使用简单的指针算法分配大小为r * c的存储块和访问元素。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int r = 3, c = 4;
int *arr = ( int *) malloc (r * c * sizeof ( int ));
int i, j, count = 0;
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
*(arr + i*c + j) = ++count;
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
printf ( "%d " , *(arr + i*c + j));
/* Code for further processing and free the
dynamically allocated memory */
return 0;
}
输出如下:
1 2 3 4 5 6 7 8 9 10 11 12
2)使用指针数组
我们可以创建大小为r的指针数组。请注意, 从C99开始, C语言允许使用可变大小的数组。创建指针数组后, 我们可以为每行动态分配内存。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int r = 3, c = 4, i, j, count;
int *arr[r];
for (i=0; i<r; i++)
arr[i] = ( int *) malloc (c * sizeof ( int ));
// Note that arr[i][j] is same as *(*(arr+i)+j)
count = 0;
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
arr[i][j] = ++count; // Or *(*(arr+i)+j) = ++count
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
printf ( "%d " , arr[i][j]);
/* Code for further processing and free the
dynamically allocated memory */
return 0;
}
输出如下:
1 2 3 4 5 6 7 8 9 10 11 12
3)使用指向指针的指针
我们还可以使用双指针动态创建指针数组。一旦我们动态分配了数组指针, 就可以像方法2一样为每行动态分配内存。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int r = 3, c = 4, i, j, count;
int **arr = ( int **) malloc (r * sizeof ( int *));
for (i=0; i<r; i++)
arr[i] = ( int *) malloc (c * sizeof ( int ));
// Note that arr[i][j] is same as *(*(arr+i)+j)
count = 0;
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
arr[i][j] = ++count; // OR *(*(arr+i)+j) = ++count
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
printf ( "%d " , arr[i][j]);
/* Code for further processing and free the
dynamically allocated memory */
return 0;
}
输出如下:
1 2 3 4 5 6 7 8 9 10 11 12
4)使用双指针和一个malloc调用
#include<stdio.h>
#include<stdlib.h>
int main()
{
int r=3, c=4, len=0;
int *ptr, **arr;
int count = 0, i, j;
len = sizeof ( int *) * r + sizeof ( int ) * c * r;
arr = ( int **) malloc (len);
// ptr is now pointing to the first element in of 2D array
ptr = ( int *)(arr + r);
// for loop to point rows pointer to appropriate location in 2D array
for (i = 0; i < r; i++)
arr[i] = (ptr + c * i);
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
arr[i][j] = ++count; // OR *(*(arr+i)+j) = ++count
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
printf ( "%d " , arr[i][j]);
return 0;
}
输出如下:
1 2 3 4 5 6 7 8 9 10 11 12
如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请发表评论。
更多C语言相关内容请参考:lsbin - IT开发技术:https://www.lsbin.com/
查看以下更多C语言的内容:
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。