简体   繁体   中英

How to declare a Global variable inside any function in 'C'?

I want to declare a global variable inside a main() function...

Below is what I want the program to act like

#include<stdio.h>
int a[6];
int main()
{
  int n;
  scanf("%d",&n);
}

I want to create an array of user given size (here n-size) and I want to access that array globally. So instead of creating array of size '6' outside the main() function, I want to create array of 'n' size globally instead of passing array whenever function is called...

You can declare a pointer as global variable and assign buffer to that in main() .

#include<stdio.h>
#include<stdlib.h>
int *a;
int main()
{
  int n;
  scanf("%d",&n);
  a = calloc(n, sizeof(*a)); /* calloc() initializes the allocated buffer to zero */
  if (a == NULL)
  {
    /* calloc() failed, handle error (print error message, exit program, etc.) */
  }
}

You may want to use an array allocated into the heap by using malloc

#include<stdio.h>
int *a;
int main()
{
  int n;
  scanf("%d", &n);
  a = malloc(sizeof(*a) * n);
  if(a == NULL) {
      // malloc error
  }

  // use your array here

  free(a); // at the end of the program make sure to release the memory allocated before
}

You cannot do that.

The closest you can get it, define a pointer in file scope (ie, global), allocate memory to it by using allocator function ( malloc() and family) and use the same pointer in other function calls as necessary. As the lifetime of the allocated memory is until deallocated programmatically (passed to free() ), other functions can make use of the allocated memory.

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