如何下一个2D(3D ...)阵列使用malloc分配时的空间? [英] How does C allocate space for a 2D (3D...) array when using malloc?

查看:200
本文介绍了如何下一个2D(3D ...)阵列使用malloc分配时的空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有理解Ç如何为2D(或更多维)数组分配空间的一个问题,尤其是当我们使用的malloc 等等。在例如这个问题。

I am having a problem understanding how C allocates space for a 2D (or more dimensional) array, especially when we use malloc and the like. Take the program in this question for example.

的指针的一维数组首先被定义,则指针1D数据(在这种情况下,串)被放置在第一一维阵列的盒每一个的阵列。因此不能保证整个二维阵列邻接(在previous行的最后一个单元接着下一行的第一个单元)。每个数据一维数组可以很遥远,只是他们的三分球是连续的。我是正确还是我失去了一些东西?我真的AP preciate如果你能帮助我澄清这一点。

A one-dimensional array of pointers is first defined, then pointers to arrays of 1D data (in this case strings) are put in each one of boxes of the first 1D array. So there is no guarantee that the whole 2D array is contiguous (the last cell of the previous row is followed by the first cell of the next row). Each 1D array of data can be very distant, only their pointers are contiguous. Am I correct or am I missing something? I would really appreciate if you could help me clarify this.

推荐答案

有这样做,这取决于你如何去访问它的各种方法。您可以确保该数组的主体是连续的,也能够避免。对于字符串数组,你经常不使阵列的连续体理会。对于整数或双打2D(ETC)阵列,你平时做阵列的连续体。

There are various ways of doing it, depending on how you're going to access it. You can ensure that the main body of the array is contiguous, or you can avoid that. For arrays of strings, you often don't bother with making the body of the array contiguous. For 2D (etc) arrays of integers or doubles, you usually do make the body of the array contiguous.

在例子中,数组的数据类型是泛型类型 T ,假定数字让数组元素可分配 0 。这些例子并不错误检查内存分配;他们在生产中应code。

In the examples, the data type of the array is the generic type T, assumed to be numeric so the array elements can be assigned 0. The examples do not error check the memory allocations; they should in production code.

int n1 = 5;
int n2 = 6;

T *a = malloc(n1 * n2 * sizeof(T));

for (int i = 0; i < n1; i++)
    for (int j = 0; j < n2; j++)
        a[i * n2 + j] = 0;

free(a);

双标数组访问 - 连续数组身体

int n1 = 5;
int n2 = 6;

T **a = malloc(n1 * sizeof(T*));
T  *b = malloc(n1 * n2 * sizeof(T));

for (int i = 0; i < n1; i++)
    a[i] = &b[i * n2];

for (int i = 0; i < n1; i++)
    for (int j = 0; j < n2; j++)
        a[i][j] = 0;

free(b);
free(a);

双标数组访问 - 不连续阵列体

int n1 = 5;
int n2 = 6;

T **a = malloc(n1 * sizeof(T*));

for (int i = 0; i < n1; i++)
    a[i] = malloc(n2 * sizeof(T));

for (int i = 0; i < n1; i++)
    for (int j = 0; j < n2; j++)
        a[i][j] = 0;

for (int i = 0; i < n1; i++)
    free(a[i]);
free(a);

这篇关于如何下一个2D(3D ...)阵列使用malloc分配时的空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆