与malloc的混淆 [英] Confusion with malloc
问题描述
我试图理解如下的C代码:
I'm trying to understand a piece of C code which is as follows:
#define DIM2( basetype, name, w1 ) basetype (*name)[w1]
int mx = 10; //number of rows per processor
int my = 100; //number of cols
DIM2 (double, f, my);
f = (typeof (f)) malloc (2 * mx * sizeof (*f));
如果我是对的,则使用DIM2创建一个(d = 100)双精度指针的1-d数组. 我无法理解malloc又会发生什么?是否需要两个这样的声明?
If I'm correct, with DIM2 a 1-d array of (size=100) pointers to double is created. I'm not able to understand what happens again with malloc? Is it necessary for two such statements?
是否可以通过其他任何方式来实现上面最后两行代码中发生的一切?
Is there any alternative way to achieve what happens in the last two lines of code above in any other way?
推荐答案
该宏的计算结果为:
double (*f)[my];
是double数组的指针,而不是double数组的指针.
which is a pointer to array of double, not an array of pointer to double.
malloc
分配一个2 * mx * <whatever
f points to>
数组(即一个double数组).不知道为什么它分配的条目数是mx
给定的两倍,但这就是它的作用.
malloc
allocates an array of 2 * mx * <whatever
fpoints to>
(i.e. an array of double). Not sure why it would allocate twice as many entries as given by mx
, but that's what it does.
因此,f
之后指向第一个 double数组.它有效地分配了一个 true 二维数组. (不是经常混淆的 double指针数组).
So, f
points to the first array of double afterwards. It effectively allocates a true 2 dimensional array. (not the often confused array of pointers to double).
请注意,malloc
的强制转换在C语言中是不好的做法.
Note that the cast of malloc
is bad practise in C.
注释:由于没有太多的键入,并且宏没有添加特定的信息,因此实际上是一种不好的做法.更糟糕的是,它隐藏了混淆代码的指针语义.建议不要使用它,而最好是明确的.这甚至没有更多的输入内容.
Comment: As there is not less typing and the macro does not add specific information, it is actually bad practise. Worse is it hides the pointer semantics obfuscating the code. Recommendation is not to use it, but better be explicit; this is even not more typing.
Update: There is currently an argument if sizeof(*f)
presents _undefined behaviour, because
f` is used uninitialized here. While I see a flaw in the standard here which should be more precise, you might better play safe and use an explicit expression:
f = malloc (2 * mx * my * sizeof (double))
这篇关于与malloc的混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!