【发布时间】:2021-12-25 00:57:07
【问题描述】:
我需要处理可变数量的固定大小数组。更具体地说,N 点在 K 维空间中,我事先知道 K,但在编译时我不知道 N。 所以我想使用一个指向固定大小数组的指针,并在运行时为N个K维点分配空间。
在 C 语言中,我可以使用 malloc 分配所述指针。下面的示例test.c,为简单起见,其中维度为 3:
#include <stdlib.h>
#include <stdio.h>
#define DIMENSIONS 3
typedef float PointKDimensions[DIMENSIONS];
void do_stuff( int num_points){
PointKDimensions *points;
points = malloc(num_points * sizeof(PointKDimensions));
points[5][0] = 0; // set value to 6th point, first dimension
points[5][1] = 1.0; // to second dimension
points[5][2] = 3.14; // to third dimension
return;
}
int main(){
do_stuff(10); // at run-time I find out I have 10 points to handle
return 0;
}
我可以用gcc test.c 编译它而不会出错,并且运行时不会出现分段错误。
但是,如果我尝试使用 C++ mv test.c test.cpp 实现相同的行为,然后是 g++ test.cpp,我会得到:
test.cpp: In function ‘void do_stuff(int)’:
test.cpp:10:18: error: invalid conversion from ‘void*’ to ‘float (*)[3]’ [-fpermissive]
10 | points = malloc(num_points * sizeof(float) * DIMENSIONS);
| ~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| |
| void*
向上搜索,发现C++并没有对malloc做隐式转换,所以我把malloc改成:
points = (float*) malloc(num_points * sizeof(float) * DIMENSIONS);
然后错误变成:
test.cpp: In function ‘void do_stuff(int)’:
test.cpp:10:12: error: cannot convert ‘float*’ to ‘float (*)[3]’ in assignment
10 | points = (float*) malloc(num_points * sizeof(float) * DIMENSIONS);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| |
| float*
但我找不到一种方法来进行适当的转换/转换来解决这个错误。例如,(float**) 也与 float(*)[3] 不同。
关于如何在 C++ 中为指向固定大小数组的指针分配空间有什么建议吗?
【问题讨论】:
-
不要在 C++ 中使用 malloc。如果您想要一个运行时大小的数组,请使用
std::vector。