There is no nul character in the array "b". There are only three elements in "b" and you initialize all them properly to a non-nul value. Any output you see as a result of the calls to printf are the result of undefined behavior and there is no other explanation.
Why the null value is stored only for character array but after the last + 1 index?

In the following program, why the null character of the character array 'b' is displayed at the 4th index but not displayed for integer and string arrays?
#include <stdio.h>
int main()
{
int a[3] = {1, 2, 3};
char b[3] = {'a', 'b', 'c'};
char c[3] = "abc";
printf("%d\n", a[4]);
printf("%d\n", b[4]);
printf("%d", c[4]);
return 0;
}
Developer technologies | C++
Developer technologies | Visual Studio | Other
2 answers
Sort by: Most helpful
-
-
Minxin Yu 13,501 Reputation points Microsoft External Staff
2023-08-14T08:40:37.4533333+00:00 Since array out-of-bounds is undefined behavior, different compilers will have different results. This is why you get weird results.
I built the program using GCC.
Output a[4], b[4] to b[6], c[4]:
And Visual Studio Output:
Since GCC was used in Visual Studio Code and online test website, instead of Visual Studio's MSVC, you need to ask the explanation of the compilation results on the GCC forum.
Best regards,
Minxin Yu
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.