2

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

#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;
}
4

4 回答 4

5

You can initialise any particular element of the struct array.

For example:

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

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

This is called Designated Initializers which used to be a GNU extension before C99 adapted it and is also supported in standard C since C99.

于 2012-05-19T12:56:17.043 回答
2

Since you are talking about a variable in file scope, here, you don't have to do anything, since such variables are always initialized by 0 if you don't provide an explicit initializer.

于 2012-05-19T12:55:36.320 回答
1

In C all static and extern variables are initialized to 0 unless explicitly initialized otherwise.

于 2012-05-19T12:55:17.193 回答
1

在 C 中,一旦你初始化了一个结构/数组的一部分,你就用 0 来初始化它的其余部分。

你应该没有问题,因为你不应该首先访问未初始化的变量,并且它们的值没有定义。

于 2012-05-19T12:52:41.320 回答