malloc 二维数组的另一种方法? [英] A different way to malloc a 2D array?

查看:34
本文介绍了malloc 二维数组的另一种方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 malloc 声明一个二维数组.在互联网上查找时,所有网站都告诉声明一个 int ** 指针,然后使用 malloc 首先将各个指针分配给一维数组,然后再次使用 malloc 为各个 int 分配空间.我怀疑以这种方式声明的数组不会将其元素保存在连续的内存地址中.而以下方式仅使用一个 malloc 语句并动态分配一个二维数组,并且所有地址都根据需要是连续的.那么以下不应该是动态分配二维数组的正确方法吗?

I want to declare a 2d array using malloc. On looking up on the internet, all websites tell to declare a int ** pointer and then use malloc for first allocating the individual pointers to the 1d arrays and then use malloc again to allocate space for the individual ints. My doubt is that the array declared this way does not hold its elements in contiguous memory addresses. While the following way using only one malloc statement and dynamically allocates a 2d array and all the addresses are contiguous as required. So shouldn't the following be the correct way to dynamically allocate a 2d array?

#include <stdio.h>

int main(){
    int (*p)[2] = malloc(3 * sizeof *p);
    int i;
    int j;

        //All addresses printed here are contiguous
    for(i=0; i<3; i++){
        for(j=0; j<2; j++){
            printf("%d\t", &p[i][j]);
        }
        printf("\n");
    }
}

推荐答案

那么以下不应该是动态分配二维数组的正确方法吗?

So shouldn't the following be the correct way to dynamically allocate a 2d array?

应该,因为这种方法等价于声明一个多维的静态分配"数组.

It should, since this approach is the equivalent of declaring a "statically-allocated" array of multiple dimensions.

这样做的原因是,通过这种方式,您可以获得一个连续的内存块,这很方便(您不能在指向指针的指针上使用 memset() ,对吧?),你仍然可以让编译器为你做指针运算和数组下标计算(这也很方便).

The reason for this is that this way, you get a contiguous block of memory, which is convenient (you couldn't use memset() on a pointer-to-pointer, right?), and you still can have the compiler do the pointer arithmetic and array subscripting calculation for you (that's convenient too).

顺便说一句,如果您需要一个动态大小的数组,其范围仅在一个函数内,i.e.您不需要返回它,请考虑使用具有自动存储持续时间的 VLA(可变长度数组).

By the way, if you need a dynamically-sized array of which the scope is only within one function, i. e. you don't need to return it, consider using a VLA (variable-length array) with automatic storage duration instead.

这篇关于malloc 二维数组的另一种方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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