繁体   English   中英

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

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

我想在 main() function 中声明一个全局变量...

以下是我希望程序的行为

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

我想创建一个用户给定大小(此处为 n 大小)的数组,并且我想全局访问该数组。 因此,我不想在 main() function 之外创建大小为“6”的数组,而是想在全局范围内创建“n”大小的数组,而不是在调用 function 时传递数组...

您可以将指针声明为全局变量并将缓冲区分配给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.) */
  }
}

您可能希望通过使用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
}

你不能这样做。

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. 由于分配的 memory 的生命周期直到以编程方式释放(传递给free() ),其他函数可以使用分配的 memory。

暂无
暂无

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

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