# 如何在C语言中动态分配2D数组？代码示例

``````1  2  3  4
5  6  7  8
9  10 11 12``````

## 1)使用单个指针：

``````#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)使用指针数组

``````#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)使用指向指针的指针

``````#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``

9 声望
0 粉丝
0 条评论