简体   繁体   English

如何在“C”中的任何 function 中声明全局变量?

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

I want to declare a global variable inside a main() function...我想在 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.我想创建一个用户给定大小(此处为 n 大小)的数组,并且我想全局访问该数组。 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...因此,我不想在 main() function 之外创建大小为“6”的数组,而是想在全局范围内创建“n”大小的数组,而不是在调用 function 时传递数组...

You can declare a pointer as global variable and assign buffer to that in main() .您可以将指针声明为全局变量并将缓冲区分配给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您可能希望通过使用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. 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.由于分配的 memory 的生命周期直到以编程方式释放(传递给free() ),其他函数可以使用分配的 memory。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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