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
95 views
in Technique[技术] by (71.8m points)

c++ - Character array initialization with the first element being null

I was recently faced with a line of code and four options:

char fullName[30] = {NULL};
  1. A) First element is assigned a NULL character.

  2. B) Every element of the array is assigned 0 ( Zeroes )

  3. C) Every element of the array is assigned NULL

  4. D) The array is empty.

The answer we selected was option C, as, while the array is only initialized with a single NULL, C++ populates the rest of the array with NULL.

However, our professor disagreed, stating that the answer is A, he said:

So the very first element is NULL, and when you display it, it's displaying the first element, which is NULL.

The quote shows the question in its entirety; there was no other information provided. I'm curious to which one is correct, and if someone could explain why said answer would be correct.

question from:https://stackoverflow.com/questions/61718622/character-array-initialization-with-the-first-element-being-null

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

1 Reply

0 votes
by (71.8m points)

The question is ill-defined, but Option B seems like the most correct answer.

The result depends on how exactly NULL is defined, which depends on the compiler (more precisely, on the standard library implementation). If it's defined as nullptr, the code will not compile. (I don't think any major implementation does that, but still.)

Assuming NULL is not defined as nullptr, then it must be defined as an integer literal with value 0 (which is 0, or 0L, or something similar), which makes your code equivalent to char fullName[30] = {0};.

This fills the array with zeroes, so Option B is the right answer.

In general, when you initialize an array with a brace-enclosed list, every element is initialized with something. If you provide fewer initializers than the number of elements, the remaining elements are zeroed.

Regarding the remaining options:

  • Option C is unclear, because if the code compiles, then NULL is equivalent to 0, so option C can be considered equivalent to Option B.

  • Option A can be valid depending on how you interpret it. If it means than the remaining elements are uninitialized, then it's wrong. If it doesn't specify what happens to the remaining elements, then it's a valid answer.

  • Option D is outright wrong, because arrays can't be "empty".


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

...