Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

Array initialization C

What is the meaning of this initialization:

char arr[10] = { 0, };

I'm familiar with char arr[10] = {0}; which sets all the elements to zero, and with char arr[10] = {1,2}; which sets the first two elements to 1 and 2 (ascii) and the rest to 0. I'm not familiar with the format above. A quick test showed that it's probably just like char arr[10] = {0};, but is there other meaning I'm not aware of?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From How to initialize all members of an array to the same value?:

Initialize all members to the same value:

int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };

Elements with missing values will be initialized to 0:

int myArray[10] = { 1, 2 }; //initialize to 1,2,0,0,0...

So this will initialize all elements to 0:

int myArray[10] = { 0 }; //all elements 0

In C++, an empty initialization list will also initialize every element to 0:

int myArray[10] = {}; //all elements 0 in C++

Objects with static storage duration will initialize to 0 if no initializer is specified:

static int myArray[10]; //all elements 0

If your compiler is GCC you can use following syntax:

int array[1024] = {[0 ... 1023] = 5};
int A[10] = {[0 ... 4] = 5, [5 ... 9] = 3};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...