堆分配一个二维数组(不是指针数组) [英] Heap allocate a 2D array (not array of pointers)

查看:22
本文介绍了堆分配一个二维数组(不是指针数组)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写 C 代码,我想在堆上分配 512*256 字节.为了我自己的方便,我希望能够使用语法 array[a][b]; 访问元素.没有算法来找到正确的索引.

I am writing C code and I would like to heap allocate 512*256 bytes. For my own convenience I would like to be able to access the elements with the syntax array[a][b]; no arithmetic to find the right index.

我在网上看到的每个教程都告诉我创建一个指针数组,这些指针指向数组中我想要的行数组.这意味着每个子数组都需要单独进行 malloc 和 free .我对只需要调用一次 malloc 和调用一次 free 的解决方案感兴趣.(因此所有元素都是连续的)我认为这是可能的,因为我不会构建锯齿状数组.

Every tutorial I see online tells me to create an array of pointers that point to arrays of the rows I want in my array. This means that each subarray needs to be malloc'd and free'd individually. I am interested in a solution that only requires one call to malloc and one call to free.(Thus all elements are contiguous) I think this is possible because I will not be constructing a jagged array.

如果有人可以分享声明此类数组的语法,我将不胜感激.

I would appreciate if anyone could share the syntax for declaring such an array.

推荐答案

好吧,如果你想分配一个类型的数组,你将它赋值给一个该类型的指针.

Well, if you want to allocate array of type, you assign it into a pointer of that type.

由于 2D 数组是数组的数组(在您的情况下,是一个包含 256 个字符的 512 个数组的数组),您应该将其分配给一个指向 256 个字符的数组的指针:

Since 2D arrays are arrays of arrays (in your case, an array of 512 arrays of 256 chars), you should assign it into a pointer to array of 256 chars:

char (*arr)[256]=malloc(512*256);
//Now, you can, for example:
arr[500][200]=75;

(*arr 周围的括号是让它成为一个指向数组的指针,而不是一个指针数组)

(The parentheses around *arr are to make it a pointer to array, and not an array of pointers)

这篇关于堆分配一个二维数组(不是指针数组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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