【问题标题】:How to declare a Global variable inside any function in 'C'?如何在“C”中的任何函数内声明全局变量?
【发布时间】:2021-04-13 06:49:48
【问题描述】:

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

下面是我希望程序表现的样子

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

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

【问题讨论】:

  • 这是动态内存分配方案的确切用例。

标签: arrays c variables scope global


【解决方案1】:

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

【讨论】:

  • 我们不能使用“extern”关键字吗?\
【解决方案2】:

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

【讨论】:

  • 如果我们使用“extern”关键字呢?
  • extern 关键字用于处理多个文件,但情况并非如此
【解决方案3】:

你不能这样做。

您可以获得最接近的,在文件范围内定义一个指针(即全局),使用分配器函数(malloc() 和系列)为其分配内存,并根据需要在其他函数调用中使用相同的指针。由于分配内存的生命周期直到以编程方式解除分配(传递给free()),其他函数可以使用分配的内存。

【讨论】:

    猜你喜欢
    • 2014-01-17
    • 2012-09-01
    • 2011-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-30
    • 2014-10-30
    相关资源
    最近更新 更多