Search code examples
arrayscvariablesscopeglobal

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...


Solution

  • 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
    }