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

Categories

0 votes
525 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...