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

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

问题描述

我写C code和我想堆上分配512 * 256字节。对于我自己的方便,我想能够访问与语法数组中的元素[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'd。我感兴趣的是,只需要调用一次malloc和一个呼叫免费的解决方案。(因此,所有的元素都是连续的),我认为这是可能的,因为我不会构建一个锯齿形数组。

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.

我想AP preciate如果有人可以共享语法声明这样的一个数组。

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.

由于二维数组是数组的数组(在你的情况下,512阵列256字符数组),你应该将其分配到一个指向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天全站免登陆