关于c:如何在C语言中动态分配2D数组代码示例

63次阅读

共计 2132 个字符,预计需要花费 6 分钟才能阅读完成。

以下是在堆上创立 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 语言的内容:

  • C 语言 exec 函数家族:https://www.lsbin.com/3438.html
  • C 语言 extern 关键字艰深解释:https://www.lsbin.com/2950.html
  • C 语言中的 scanset 是什么?:https://www.lsbin.com/2363.html

正文完
 0