分配6xNxN阵列 [英] Allocate 6xNxN array

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

问题描述

我有一个变量N.我需要一个6xNxN数组.

I have a variable N. I need a 6xNxN array.

类似这样的东西:

int arr[6][N][N];

但是,显然,这是行不通的.

But, obviously, that doesn't work.

我不确定如何分配它以便可以访问,例如如果N为5,则为arr[5][4][4];如果N为24,则为arr[5][23][23].

I'm not sure how I'd go about allocating this so that I can access, e.g. arr[5][4][4] if N is 5, and arr[5][23][23] if N is 24.

请注意,N永远不会更改,因此我永远不必realloc修改arr.

Note that N will never change, so I'll never have to reallocate arr.

我该怎么办? int ***arr = malloc(6 * N * N * sizeof(int));可以工作吗?

What should I do? Will int ***arr = malloc(6 * N * N * sizeof(int)); work?

推荐答案

对这一行的声明进行简单的更改并保持malloc即可轻松解决您的问题.

Making a simple change to the declaration on this line and keeping the malloc can easily solve your problem.

int ***arr = malloc(6 * N * N * sizeof(int));

但是,int ***是不必要的(也是错误的).使用易于分配的平面数组:

However, int *** is unnecessary (and wrong). Use a flat array, which is easy to allocate:

int *flatarr = malloc(6 * N * N * sizeof(int));

这适用于三个维度,您可以访问flatarr[(X*N*N) + (Y*N) + Z],而不是像问题中那样访问arr[X][Y][Z].实际上,您甚至可以编写一个方便的宏:

This works for three dimensions, and instead of accessing arr[X][Y][Z] as in the question, you access flatarr[(X*N*N) + (Y*N) + Z]. In fact, you could even write a handy macro:

#define arr(X,Y,Z) flatarr[((X)*N*N) + ((Y)*N) + (Z)]

基本上,这是我使用我的语言 Cubically 所做的事情,以允许使用多个尺寸的多维数据集.感谢编程难题&代码高尔夫用户丹尼斯给了我这个主意.

This is basically what I've done in my language Cubically to allow for multiple-size cubes. Thanks to Programming Puzzles & Code Golf user Dennis for giving me this idea.

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

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