C编程,int a[N]={0};这句话的含义?

标签 c arrays initialization

对于著名的问题。

有 100 个人围成一圈,编号从 1 到 100。第一个人拿着剑,顺时针杀死站在他旁边的人,即 1 杀 2,以此类推。最后存活下来的数字是哪一个?最后一个数字是哪个?

在下面的 C 代码中解决这个问题。

void main(){
    int i=0, j; //i has the sword, j gets killed.
    int a[N]={0}; //0=not killed
    while(1){
        if(i != N-1) j = i + 1;
        else j = 0;
        while(a[j])
            if((j + 1) == N) j = 0; //loop back to 0
            else j++; //skip over the killed people
        if(i==j){ //if i is the only one left, stop
            printf("\n\n\n%d is left!", i+1);
            return;
        }
        a[j] = 1; //kill j
        printf(" %d kills %d.", i+1, j+1);
        if(j != N-1) i = j + 1;
        else i=0;
        while(a[i])
            if((i + 1) == N) i = 0;
            else i++;
    }
}

请告诉我 int a[N]={0}; 的含义//0=没有在第 1 行被杀死。 6 谢谢。

最佳答案

在您的代码中,

 int a[N]={0};

正在将数组a所有成员初始化为0。

根据 C11 标准,第 §6.7.9 章,初始化,(强调我的)

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

并且,对于静态存储类型int的初始化器值,它是算术类型

[...] if it has arithmetic type, it is initialized to (positive or unsigned) zero;

a是一个int类型的数组,因此它的所有成员都被初始化为0作为值。 a[0] 将显式初始化为 0 (已提供),其余部分将获得隐式初始化。

FWIW,N 必须是编译时常量值,例如

#define N 50 //or any value

为了让它发挥作用。

关于C编程,int a[N]={0};这句话的含义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37237592/

相关文章:

c++ - K阶统计搜索

arrays - 在postgresql中将列从字符串更改为字符串数组

java - 为什么不能调用已经在循环中初始化并预先声明的变量?

arrays - 你如何在 matlab 中初始化一个包含 90 个 '0' 的数组?

c - 打印出堆栈指针的值

c - 来自 directx 应用程序的 Bitblt

c - CreateFile() 和 CreateFileA() 有什么区别?

c - 如何在字符串中搜索字符串? C

ios - 按索引移动数组中的元素

ruby - 当我可以继承而不使用它时,为什么我们在 ruby​​ 中使用 super?