分配的二维阵列 [英] Allocate two-dimensional array

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

问题描述

我如何分配使用的malloc双维数组
这是我目前的code:

How can I allocate a bi-dimensional array using malloc? This is my current code:

typedef struct object product, *pprod;
struct object{
    int type;
    int quantity;
    pprod next;
};

pprod t[4][3];

非常感谢你的帮助。

Thanks a lot for your help.

推荐答案

要以这样的方式分配存储器的布局是与正常的二维阵列兼容 - 或数组的数组 - 你需要一个指针的数组适当的大小,

To allocate memory in such a way that the layout is compatible with a normal two-dimensional array - or array of arrays - you need a pointer to an array of appropriate size,

pprod (*t)[m] = malloc(n * sizeof *t);

因此​​, T 是一个指向 M 类型的元素 pprod ,你可以简单地使用它

Thus t is a pointer to arrays of m elements of type pprod, and you can simply use it

t[i][j]

就好像宣布

pprod t[n][m];

(如的malloc 不返回 NULL )。

该分配分配的内存连续块,不像分配 pprod ** 会。

This allocation allocates a contiguous block of memory, unlike allocating a pprod ** would.

(注意:如果 M 不是一个编译时间常数,即要求编译器支持变长数组,它不会与MSVC工作。)

(Note: If m is not a compile-time constant, that requires that the compiler supports variable length arrays, it would not work with MSVC.)

这篇关于分配的二维阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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