Is compiler always takes care of adding '\0' in character arrayinitialization ?

Discussion in 'C Programming' started by Shivanand Kadwadkar, Jan 9, 2011.

  1. I was trying to test what is the output of program if i dont reserve
    any space for '\0' in the character array that i have declared.
    ---------------------------------------------------------------------------------
    #include<stdio.h>

    int main()
    {

    char var1='A',var2[2]="BC",var3='E';

    printf("\n var1=%c var2=%s var3=%c and sizeof(var2)=
    %d",var1,var2,var3,sizeof(var2));

    return 0;
    }



    output:
    var1=A var2=BC var3=E and sizeof(var2)=2

    in memory they are allocated in following way:
    FFF5 : A
    FFF4 : // i havent checked what is here ? assumed it is \0
    FFF3 :C
    FFF2 :B
    FFF1 : E

    my question here is, is compiler implicitly reserves a byte for '\0'
    when we dont reserve any space for '\0' as the case with var2 always?
    ---------------------------------------------------------------------------------
    Shivanand Kadwadkar, Jan 9, 2011
    #1
    1. Advertising

  2. Shivanand Kadwadkar

    Eric Sosman Guest

    On 1/9/2011 1:36 PM, christian.bau wrote:
    > [...]
    > If your array has a size big enough for the characters and a '\0' plus
    > possibly more characters, '\0' is added.
    >
    > char a [4] = "ABC";
    > char a [10000] = "ABC"; // First four chars are 'A', 'B', 'C' and
    > '\0'.


    The array will hold 'A', 'B', 'C', and 9997 '\0' chars. Loosely
    speaking, if any part of an array is initialized, the entire array is
    initialized. Unmentioned elements -- in this case, the final 9996 --
    receive "zeroes of the appropriate kind."

    --
    Eric Sosman
    lid
    Eric Sosman, Jan 9, 2011
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Gregory Huffman

    How to include don't care minterms

    Gregory Huffman, Jan 26, 2004, in forum: VHDL
    Replies:
    3
    Views:
    7,410
    Gregory Huffman
    Jan 28, 2004
  2. bittor

    Don't care signals

    bittor, Feb 14, 2005, in forum: VHDL
    Replies:
    1
    Views:
    5,340
    Tim Hubberstey
    Feb 14, 2005
  3. mit
    Replies:
    1
    Views:
    413
    Scott M.
    Jan 8, 2006
  4. joes
    Replies:
    2
    Views:
    991
    Daniel Pitts
    May 25, 2007
  5. Replies:
    29
    Views:
    1,155
Loading...

Share This Page