通过参数引用更新C中的全局变量 [英] Update global variable in C via reference by parameter

查看:47
本文介绍了通过参数引用更新C中的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

short int PC = 0;

int main() {
    foo(&PC) ;
}

void foo(short int PC) {
    PC++;
}

如何成功更新PC的全局变量?

How do I successfully update the global variable of PC?

注意:必须将PC作为参数传递,并且需要通过该参数修改全局变量.

Note: PC must be passed as a parameter and the global variable needs to be modified via the parameter.

您可以告诉我,我是C语言的新手,并试图了解 * & 之间的区别.任何帮助将不胜感激.

As you can tell I am new to C and am trying to understand the difference between * and &. Any help would be much appreciated.

推荐答案

您只需要将参数用作指针:

You just need to take the argument as a pointer:

short int PC = 0;

void foo(short int *pc) {
    (*pc)++;
}

int main() {
    foo(&PC) ;
}

我将 foo()移到了 main()上方,因为在C语言中,您必须先声明事物,然后再使用它们.如果您愿意,可以通过在顶部说 void foo(); 来声明它,并在下面保留定义.

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.

这篇关于通过参数引用更新C中的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆