问题
short int PC = 0;
int main() {
foo(&PC) ;
}
void foo(short int PC) {
PC++;
}
How do I successfully update the global variable of PC?
Note: PC must be passed as a parameter and the global variable needs to be modified via the parameter.
As you can tell I am new to C and am trying to understand the difference between * and &. Any help would be much appreciated.
回答1:
You just need to take the argument as a pointer:
short int PC = 0;
void foo(short int *pc) {
(*pc)++;
}
int main() {
foo(&PC) ;
}
I moved foo() above main() because in C you have to declare things before they are used. If you prefer you could forward declare it by saying void foo(); at the top and leave the definition below.
来源:https://stackoverflow.com/questions/39715740/update-global-variable-in-c-via-reference-by-parameter