我看过很多关于 c++/java 的帖子,但没有看到关于 C 的帖子。是否可以在运行时动态地为 X 类型的数组分配内存?例如,在伪中,
switch(data_type)
case1:float, create a new array of floats to use in the rest of the program
case2:int, create new array of ints to use in the rest of the program
case3:unsigned, ....
// etc.
在我的程序中,我在运行时从文本头文件中确定数据类型,然后我需要创建一个适当的数组来存储/操作数据。 C 中是否存在某种泛型类型?
编辑:我需要动态创建并决定应该创建哪个数组。
谢谢, 花花公子
最佳答案
假设您计算了数组所需的总大小(以字节为单位),您只需分配那么多内存并将其分配给正确的指针类型即可。
例如:
void * data_ptr = malloc( data_sz );
然后您可以将其分配给您想要的任何类型的指针:
int *array1 = (int *)data_ptr;
或
float *array2 = (float *)data_ptr;
注意:malloc 在堆上分配内存,因此不会自动释放。确保在某个时候释放分配的内存。
更新
enum {
DATA_TYPE_INT,
DATA_TYPE_FLOAT,
...
};
typedef struct {
int data_type;
union {
float * float_ptr;
int * int_ptr;
...
} data_ptr;
} data;
虽然这可能允许您存储指针并告诉您应该使用哪种类型的指针,但它仍然存在不必根据数据类型分支行为的问题。这将很困难,因为编译器必须知道赋值等的数据类型。
关于c - 在 C 中动态创建一个 TYPE 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4855230/