分配二维数组的怪异方法? [英] Freaky way of allocating two-dimensional array?

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

问题描述

在一个项目中,有人推动了这条线:

In a project, somebody pushed this line:

double (*e)[n+1] = malloc((n+1) * sizeof(*e));

据说创建了一个 (n+1)*(n+1) 双精度的二维数组.

Which supposedly creates a two-dimensional array of (n+1)*(n+1) doubles.

据说,我说,因为到目前为止,我问过的任何人都不能告诉我这究竟是做什么的,也没有告诉我它来自哪里或为什么它应该起作用(据称,它确实如此,但我还没买).

Supposedly, I say, because so far, nobody I asked could tell me what this does, exactly, nor where it originated from or why it should work (which allegedly, it does, but I'm not yet buying it).

也许我遗漏了一些明显的东西,但如果有人能向我解释上面的内容,我将不胜感激.因为就我个人而言,如果我们使用我们真正理解的东西,我会感觉好多了.

Perhaps I'm missing something obvious, but I'd appreciate it if somebody could explain above line to me. Because personally, I'd feel much better if we'd use something we actually understand.

推荐答案

变量 e 是指向 n + 1 类型元素的数组的指针双重.

The variable e is a pointer to an array of n + 1 elements of type double.

e 上使用解引用运算符为您提供 e 的基本类型,它是"n + 1n + 1 类型元素的数组 <代码>双".

Using the dereference operator on e gives you the base-type of e which is " array of n + 1 elements of type double".

malloc 调用简单地采用 e 的基本类型(上面解释过)并获取其大小,将其乘以 n + 1,并将该大小传递给 malloc 函数.本质上分配一个 n + 1 数组的 n + 1double 元素的数组.

The malloc call simply takes the base-type of e (explained above) and gets its size, multiplies it by n + 1, and passing that size to the malloc function. Essentially allocating an array of n + 1 arrays of n + 1 elements of double.

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

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