Sir*_*tty 2 c arrays pointers casting
我正在使用一些遗留代码来广泛使用这种东西:
// Allocate a look-up-table of pointers.
long *pointerLUT = (long *) malloc(sizeof(long) * numPointers);
...
// Populate the array with pointers.
for (int i=0; i<numPointers; i++) {
pointerLUT[i] = (long) NewFoo();
}
...
// Access the LUT.
Foo *foo = (Foo *) pointerLUT[anIndex];
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,这会分配一个long数组,并想要使用它们通用指针存储.
Q1.这种方法安全吗?
Q2.风格方面,如何改进?它需要吗?(类型转换让我心中的恐惧咆哮.)
谢谢.
A1:你应该更换long使用void *,因为sizeof(long)不一定是一样的sizeof(void *).例如,这不适用于64位Windows安装程序,其中long32位,指针为64位.
A2:如果你使用C并且void *你不需要使用类型转换,因为可以从中转换为void *.
编辑:我错过了他在问题中所说的“通用指针存储”的地方。对于这种情况,这个答案是不正确的。
如果您正在使用指向 Foo 的指针,那么这就是您的代码应该说的。
// Allocate a look-up-table of pointers.
Foo **pointerLUT = (Foo **) malloc(sizeof(Foo *) * numPointers);
// Populate the array with pointers.
for (int i=0; i<numPointers; i++) {
pointerLUT[i] = NewFoo(); // NewFoo() should return (Foo *)
}
// Access the LUT.
Foo *foo = pointerLUT[anIndex];
Run Code Online (Sandbox Code Playgroud)