分配内存的二维数组使用malloc调用的最小数量 [英] Allocate memory for 2D array with minimum number of malloc calls

查看:156
本文介绍了分配内存的二维数组使用malloc调用的最小数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是低于code段使用)的最小数量的malloc(呼叫分配的二维数组的内存。

I am using the below code snippet to allocate memory for 2D array using minimum number of malloc() calls.

我想用标,对访问数组[I] [J]。

I want to access the array using subscripts, p[i][j].

#define ROW 3
#define COL 2

int main()
{
    void **ptr = malloc( ROW*COL* sizeof(int) );

    int (*p)[COL] = ptr;

    int i, j;

    for( i = 0; i < ROW; ++i )
            for( j = 0; j < COL; ++j )
                    scanf("%d", &ptr[i][j]);

    for( i = 0; i < ROW; ++i )
    {
            for( j = 0; j < COL; ++j )
                    printf("%d ", p[i][j]);
            printf("\n");
    }

    return 0;
}

该计划是正确输出无论是输入。

The program is outputting correctly whatever is the input.

但是,它显示运行时错误。为什么呢?

But, it is showing Runtime error . Why?

推荐答案

如果数组尺寸(在你的例子如)在编译时已经知道,那么你的确可以在一个分配内存的malloc 电话。但是,你必须使用正确的指针类型访问内存。你的情况,这将是你的 P 指针。您 P 指针正确声明,但由于某种原因被完全忽视它的存在在 scanf函数,并使用 PTR 代替。

If the array dimensions are known at compile-time (as in your example), then you can indeed allocate memory in one malloc call. But you have to use the proper pointer type to access that memory. In your case that would be your p pointer. You p pointer is declared correctly, but you for some reason are completely ignoring its existence in scanf and using ptr instead.

停止尝试使用 PTR 数组访问。使用 P 。访问数组元素为 P [i] [j]的,它应该工作。

Stop trying to use ptr for array access. Use p. Access your array elements as p[i][j] and it should work.

其实,我就会改掉 PTR 完全,做以如下方式分配内存

In fact, I would get rid of ptr entirely and do memory allocation in the following way

int (*p)[COL] = malloc(ROW * sizeof *p);

此外,由于的两个的尺寸是在编译时已知,实际上你可以分配为

Moreover, since both dimensions are known at compile time, you can actually allocate it as

int (*p)[ROW][COL] = malloc(sizeof *p);

但在这种情况下,你必须记住要访问数组为(* P)[i] [j]的(注意 * )。选择哪种方法你preFER。

but in this case you'll have to remember to access the array as (*p)[i][j] (note the *). Choose whichever method you prefer.

这篇关于分配内存的二维数组使用malloc调用的最小数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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