What is the default value of a char in an uninitialized array, in C?

前端 未结 2 1631
闹比i
闹比i 2021-01-03 04:49

Given the following declaration:

char inputBuffer[12];

What is the default value of either char within the array? I\'m interested in knowing thi

相关标签:
2条回答
  • 2021-01-03 05:09

    If char inputBuffer[12]; is global or static, it is initialized with \0

    char inputBuffer1[12];  /* Zeroed */
    static char inputBuffer1[12];  /* Zeroed */
    
    int fn()
    {
      static char inputBuffer3[12];  /* Zeroed */
    }
    

    If it is local to function, it contains garbage value.

    int fn2()
    {
      char inputBuffer4[12];  /* inderminate value */
    }
    

    Quoting from ISO/IEC 9899:TC2 Committee Draft — May 6, 2005 WG14/N1124

    Section 6.7.8 Initialization (emphasis mine)

    10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:
    — if it has pointer type, it is initialized to a null pointer;
    — if it has arithmetic type, it is initialized to (positive or unsigned) zero;
    — if it is an aggregate, every member is initialized (recursively) according to these rules;
    — if it is a union, the first named member is initialized (recursively) according to these rules.

    0 讨论(0)
  • 2021-01-03 05:16

    The array elements have indeterminate value except if the array it is defined at file-scope or have static storage-class specifier then the array elements are initialized to 0.

     #include <stdio.h>
    
     char inputBuffer1[12];          // elements initialized to 0
     static char inputBuffer2[12];   // elements initialized to 0
    
     void foo(void)
     {
         char inputBuffer3[12];         // elements have indeterminate value!
         static char inputBuffer4[12];  // elements initialized to 0
     }
    
    0 讨论(0)
提交回复
热议问题