C中的struct数组初始化

joh*_*han 2 c arrays struct initialization

这是我的代码的一部分.我想初始化arraylist[0]as arraylist[0].x = 0arraylist[0].y = 0.我不需要初始化struct数组的其余部分.我该怎么做?谢谢.

#include <stdio.h>
struct example {
    int x;
    int y;
};
struct example arraylist[40];

int main(int argc, char *argv[]){
    printf("%d\n %d\n", arraylist[0].x, arraylist[0].y);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

P.P*_*.P. 5

您可以初始化struct数组的任何特定元素.

例如:

struct example arraylist[40] = { [0]={0,0}}; //sets 0th element of struct

struct example arraylist[40] = { [5]={0,0}}; //sets 6th element of struct
Run Code Online (Sandbox Code Playgroud)

这被称为指定初始化器,它在C99改编之前曾经是GNU扩展,并且自C99起也在标准C中得到支持.

  • 但是,一旦为对象的任何部分创建了初始化器,就会初始化整个对象("适当类型的零"). (4认同)