如何将不同的结构定义为单个变量

时间:2015-08-03 09:47:24

标签: c

我根据条件声明一个变量:

if(abc == 2)
{
price* x;
    x = (price *)malloc(2 * sizeof(price*));
}
else if(abc == 3)
{
store* x;
    x = (store *)malloc(2 * sizeof(store*));
}

// x is getting used in other function
xyz(&x);

编译时,它抛出错误:错误:' x'在这方面没有申明。据我所知,由于x未在函数范围内定义,因此抛出错误。

我试图声明void * x,但这也没有用。有什么方法可以实现这个目标吗?

2 个答案:

答案 0 :(得分:2)

您必须在x之前声明if。问题是变量的范围不是类型!

答案 1 :(得分:1)

好像你想要

void* x = 0;

if(abc == 2)
{
    x = (price *)malloc(2 * sizeof(price*));
}
else if(abc == 3)
{
    x = (store *)malloc(2 * sizeof(store*));
}

顺便说一句,大小或类型似乎在malloc行中是可疑的。

我想你想要

x = (price **)malloc(2 * sizeof(price*));

x = (price *)malloc(2 * sizeof(price));