【发布时间】:2014-12-27 17:37:38
【问题描述】:
我尝试编写一个函数,在数据结构中找到 void 指针。该函数必须将void* 转换为任何类型的结构。
假设我编写了一个结构,我以 void 指针 的形式将其存储在我的数据结构中。然后我调用该函数,该函数打印所有存储的数据元素的信息。 为此,函数必须知道它应该转换为哪种类型。
所以我的问题是:是否有可能以某种方式以参数的形式为函数提供所需的信息?
示例代码:
typedef struct{
int a, b
} teststruct;
void DSOut(datastructure* ds, datatypeinfo dt){
//...
//search for data in ds
//...
//if data is found cast it to the type defined in dt
//and print out the a and b fields
}
int main(){
datastructure* ds = DSCreate(4, 3); //can hold any type of data,
//but should hold just one at a time
//4 and 3 are just example parameters
teststruct ts;
ts.a = 4;
ts.b = 10;
teststruct ts2;
ts2.a = 6;
ts2.b = 12;
//Add the teststructs to the data-structure
DSAdd(2, 2, ts); //the numbers are just for example
DSAdd(4, 1, ts2);
datatypeinfo dt = teststruct; //stores the type teststruct for DSOut
DSOut(ds, dt); //function, that prints information of all added teststructs
return 0;
}
在此示例中,DSOut(x,y) 应打印以下内容:
- on position 2, 2 is an element which holds following data: 4, 10.
- on position 4, 1 is an element which holds following data: 6, 12.
你认为这可能吗?
【问题讨论】:
-
这是使用
void指针的问题之一 - 您会丢失有关指针指向的数据类型的所有信息。 -
C 没有办法进行动态类型声明,所有类型都必须静态指定。您可以做的最好的事情是一个固定的数据类型列表,您可以使用
if/then/else或switch进行处理。 -
请参阅stackoverflow.com/questions/18577404/… 了解我所说的示例。
标签: c parameters casting type-conversion custom-data-type