0

I am declaring one variable based on the condition:

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);

while compile, it is throwing error: error: 'x' was not declared in this scope. I understand that, since x is not defined in the function scope, it is throwing error.

I tried to declare void* x, but that also didn't work. Is there any way we can achieve this?

5
  • Why didn't void * work? It will work if you do it correctly. What problems you face when using void *? Commented Aug 3, 2015 at 9:51
  • Thanks, But it is throwing error if I am using x like this: xyz(&x[0]); error: pointer of type 'void ' used in arithmetic , error: 'void' is not a pointer-to-object type Commented Aug 3, 2015 at 9:57
  • As the error says void * is an incomplete type. Pass xyz(x) instead of indexing it. I am wondering what xyz() does with x without knowing the type of x. Commented Aug 3, 2015 at 9:59
  • above code , is a sample piece of code. I didn't posted the actual code. In xyz, we need to pass the parameter like &x[0] . As of now, I have two different function for each struct , which is working fine. I am trying to refactor the code, by adding this if condition. Commented Aug 3, 2015 at 10:03
  • xyz needs to cast it back to price* or store* before it can index it. And it needs some way to know which one it points to. Commented Aug 3, 2015 at 10:04

2 Answers 2

3

You have to declare x before the if. The problem is the scope of the variable not the type!

Sign up to request clarification or add additional context in comments.

Comments

1

It seems you want

void* x = 0;

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

btw, size or type seems suspicious in malloc line.

I think you want

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

or

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

2 Comments

Thanks, But it is throwing error if I am using x like this: xyz(&x[0]); error: pointer of type 'void ' used in arithmetic , error: 'void' is not a pointer-to-object type
@user1138143: What is xyz ? Is xyz(x) sufficient ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.