Monday, July 19, 2010

weird

Changing the variable init line to:

char character[10] = "a";


fixed it... but that makes me sad. They haven't covered this kind of thing yet so I feel like there should be a solution more similar to what I already did'

1 comment:

  1. What you have here is an array of characters, which is how C implements the concept of a string. You have to reserve one character spot in the array for the null-terminator, which lets any function that operates on the string know when the string is finished. In other words, your string array of size 10 can be up to 9 characters long + 1 null-terminator.

    The variable 'character' is just a pointer to the first char in your array of 10 chars. The double-quotes around "a" lets the compiler know that you're specifying a string for use as an initial value.

    The compiler has such great hospitality that it then:

    1) Statically allocates some memory (in the amount of 10 chars) to store your character array.

    2) Generates code to initialize that memory with {'a','0'}, which is the "a" you wanted and the null-terminator that is implied by your use of double quotes.

    3) Stores the pointer to the first element of your newly initialized array of chars in a variable called 'character'.

    Now, if you do this:

    char b = character[0];
    printf("%c\n",b);

    You get:

    a

    And if you do this:

    char b = character[1];
    printf("%d\n",b);

    You get:

    0

    And if you do THIS:

    char b = character[2];
    printf("%d\n",b);

    Hopefully you get:

    0

    If you get something else then your compiler is lazy (optimizing?) and decided not to mess with the other 8 chars you reserved for your array but did not use. Whatever was in that area of memory when the program loaded was left untouched and you just printed whatever garbage it happened to be.

    You can continue on in this fashion until you get to 'character[11]', in which case you either get a compiler error if your compiler is vigilant, or you get to sneak a peek at whatever happens to be in memory after your array, or you might even get a segfault. Adventure!

    ReplyDelete