Why the null value is stored only for character array but after the last + 1 index?

Debojit Acharjee 455 Reputation points
2023-08-11T12:44:30.0233333+00:00

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
{count} votes

2 answers

Sort by: Most helpful
  1. Barry Schwarz 3,746 Reputation points
    2023-08-11T16:04:49.77+00:00

    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.

    0 comments No comments

  2. Minxin Yu 13,501 Reputation points Microsoft External Staff
    2023-08-14T08:40:37.4533333+00:00

    Hi, @Debojit Acharjee

    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]:
    User's image

    And Visual Studio Output:

    enter image description here

    User's image

    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.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.