声明一个全局大小的数组

时间:2016-02-22 22:01:03

标签: c arrays coding-style

我可以在C中声​​明一个带有全局元素的数组吗? 我能用const类型声明吗? 它运行在Xcode上,但我担心它不正确,因为glob不是const类型(在静态类型上也是如此)。

#include <stdio.h>
#include <stdilib.h>

int glob;
void main (){
    int const con;
    static int stat;
    int arr[glob];
    int arr2[con];
    int arr3[stat];
}

此外,我需要练习在C代码中查找错误并更正它们进行测试(CS学生)并且无法找到它的资源。

提前谢谢。

2 个答案:

答案 0 :(得分:0)

如果未提供初始化程序,则全局和静态将自动初始化为0。然而,main的本地变量{{1}}不是,因此它的值是未定义的。

答案 1 :(得分:0)

  

我可以在C中声​​明一个带有全局元素的数组吗?

使用C99和可选的C11,支持可变长度数组(VLA) Array length must be more than 0

int glob;
void main (){
  int arr[glob];     // bad array length 0
  int arrX[glob+1];  // OK array length > 0
  

我能用const类型声明吗?

对于VLA,是的,如果数组大小的类型是const则无关紧要。

// Assume VLAs are allowed
int a[5];         // OK 5 is a constant
const int b = 4;
int c[b];         // OK
int d = 7;
int e[d];         // OK

对于非VLA,数组大小必须是常量。变量const或不变,是不合适的。

// Assume VLAs not allowed
int a[5];         // OK 5 is a constant
const int b = 4;
int c[b];         // No good, b is not a constant.
  

此外,我需要练习在C代码中发现错误并纠正它们进行测试

启用编译器的所有警告是第1步。