0

I'm trying to access an array across files, like this;

int option[NUMBER_OF_OPTIONS];
...
addition(&option[0], num1, num2); 
...
printf("%d", option[0]);

thats the first(main) file

and the second is like this;

void addition(int * option, unsigned number1, unsigned number2)
{
int total = number1 + number2;
...
*option ++;
}

Something like that. Dont worry about the addition method.

The problem is that the printf method allways prints 0, as if *option ++; is never executed/read.

How do i fix this?

By the way, I get a warning in the "*option++;" file saying: warning: value computed is not used.

How do I solve this problem?

Thank you!

1
  • This code should not even compile. What compiler are you using? Commented Jul 31, 2013 at 12:51

3 Answers 3

5

This:

*option++;

doesn't do what you think it does. What it actually means is:

*(option++);

which first applies the increment operator to the option pointer and dereferences it afterwards. The effect is:

option++;
*option; // This is a statement with no effect, hence the warning.

You need this instead:

(*option)++;
Sign up to request clarification or add additional context in comments.

8 Comments

It is valid. It is the same as *(option ++);. And the compiler already gave a warning, suspecting that something was not right.
@DanielDaranas because the effect of expression *option ++; is just option++;, an lhs variable missing. its should be like: x = *option ++;
@DanielDaranas, AnttiHaapala: The correct term is "modifiable lvalue". I corrected the answer. Other than that, the code is not valid. A warning is not enough; the code should actually not compile at all.
You're wrong about *option++ being something that shouldn't compile. If you look closely, you'll see that at the point where option is being incremented, is inside the addition() function. In that scope, option is a pointer that was passed to the function.
@ElchononEdelson You're right. A good real-life example of why shadowing a variable from an enclosing scope is a bad idea; people get confused :-)
|
2

++ has a higher priority than *. So *option ++; is the same as *(option ++);, which do nothing (that's why you get the warning).

Try this:

(*option) ++;

Comments

1

* binds looser than ++, so *option ++ = *(option++); to modify the values in array, you need to write (*option)++; that is, the suffix increment has higher precedence than the dereference operator

Comments

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.