[英]Can a variable in main function be access outside the main?
#include <stdio.h>
void foo();
int main()
{
int b = 0;
int a[6] = {1,2,3,4,5,6};
foo();
return 0;
}
void foo()
{
//write some code to print a and b
}
My Question is: 我的问题是:
How to get the local variable from outside without pass any parameter ? 如何从外部获取局部变量而不传递任何参数?
That's not possible. 那不可能 You need to pass a pointer to it to access it from a function or make it global.
您需要传递一个指向它的指针,以从一个函数访问它或使其成为全局的。
You can create two global variables and store each the values of a and b in them. 您可以创建两个全局变量并将a和b的每个值存储在其中。 In the
foo()
create two variables a and b and store values of ga and gb 在
foo()
创建两个变量a和b并存储ga和gb的值
#include <stdio.h>
void foo();
int gb,ga[6];
int main()
{
int b = 0;
int a[6] = {1,2,3,4,5,6};
gb=b;
for (int x = 0 ; x<6 ; x++)
ga[x]=a[x];
foo();
return 0;
}
void foo()
{
int a=ga;
int b[6];
for (int x = 0 ; x<6 ; x++)
b[x]=gb[x];
//now you can use a and b here
}
声明一个全局指针,并在main内,将局部变量的地址分配给该指针,并在任何地方使用它。
No we cant. 不,我们不能。 We can make public class or even another function.
我们可以公开类甚至其他功能。 As we are defining it in the main, we can't.
正如我们主要定义的那样,我们不能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.