不同的方法到malloc的二维数组? [英] A different way to malloc a 2D array?

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

问题描述

我想使用malloc声明一个二维数组。在互联网上查找,所有的网站告诉申报INT **指针,然后使用malloc为第一个人分配指针的一维数组,然后再使用malloc为单个整数分配空间。我的疑问是,数组声明这样不保持其在连续的内存地址元素。而只使用一个malloc的语句和动态以下方式分配一个二维阵列和所有的地址是连续的要求。所以不宜以下是动态分配一个二维数组的正确方法?

 的#include<&stdio.h中GT;诠释主(){
    INT(* p)的[2] = malloc的(3 * sizeof的* P);
    INT I;
    诠释J;        //这里印刷的所有地址都是连续的
    对于(I = 0; I&下; 3;我++){
        为(J = 0; J&2; J ++){
            的printf(%d个\\ t的,&安培; P [i] [j]的);
        }
        的printf(\\ n);
    }
}


解决方案

  

所以不应下面是动态分配一个二维数组的正确方法?


它不应该,,因为这个办法是的宣布多个维度的静态分配数组的等价物。

这样做的原因是,这样一来,你会得到一个连续的内存块,这是方便(你不能使用 memset的()上一个指针到终场前,对吧?),你仍然可以让编译器为你做指针算法和数组下标计算(这是太方便了)。

顺便说一句,如果你需要一个动态大小的数组其范围是只在一个函数,我。即你并不需要退货,考虑使用VLA(可变长度数组)具有自动存储时间来代替。

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.

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).

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天全站免登陆