Update global variable in C via reference by parameter

自古美人都是妖i 提交于 2020-01-30 11:22:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!