In C, you can partially initialize a struct or array, with the result that the members/elements that aren't mentioned in the initializer are zero-initialized. (C99 section 6.7.8.19). For example:-
int a[4] = {1, 2};
// a[0] == 1
// a[1] == 2
// a[2] == 0
// a[3] == 0
You can also initialize "an array of character type" with a string literal (C99 section 6.7.8.14), and "successive characters ... initialize the elements of the array". For example:-
char b[4] = "abc";
// b[0] == 'a'
// b[1] == 'b'
// b[2] == 'c'
// b[3] == ''
All pretty straightforward. But what happens if you explicitly give the length of the array, but use a literal that's too short to fill the array? Are the remaining characters zero-initialized, or do they have undefined values?
char c[4] = "a";
// c[0] == 'a'
// c[1] == ''
// c[2] == ?
// c[3] == ?
Treating it as a partial initializer would make sense, it would make char c[4] = "a"
behave exactly like char c[4] = {'a'}
, and it would have the useful side-effect of letting you zero-initialize a whole character array concisely with char d[N] = ""
, but it's not at all clear to me that that's what the spec requires.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…