简体   繁体   中英

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. In the foo() create two variables a and b and store values of ga and 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM