Gay But Not Narrow (ruakh) wrote in cprogramming,
Gay But Not Narrow
ruakh
cprogramming

Printf-ing a char[] field of a struct.

So I hadn't programmed in C for a while, so I thought I'd undertake a small just-for-fun project in it. Almost immediately, I ran into a strange wall. Behind the cut is a short program that demonstrates the problem I'm having (using GCC 3.2.3 for MinGW).

#include <stdio.h> // printf()

typedef struct {
        char s[4];
} four_bytes;

four_bytes identity(four_bytes fb)
{
        return fb;
}

int main()
{
        four_bytes fb1, fb2;

        // Initialize fb1.s to "ABC":
        fb1.s[0] = 'A';
        fb1.s[1] = 'B';
        fb1.s[2] = 'C';
        fb1.s[3] = '\0';

        // Goes crazy (prints garbage, call it a segfault):
        printf("%s\n", identity(fb1).s);

        // Goes crazy (prints garbage, call it a segfault):
        printf("%s\n", (fb2 = identity(fb1)).s);

        // Works fine - prints "ABC\n":
        fb2 = identity(fb1);
        printf("%s\n", fb2.s);

        // Works fine - prints "ABC - 0\n":
        printf("%c", identity(fb1).s[0]);
        printf("%c", identity(fb1).s[1]);
        printf("%c", identity(fb1).s[2]);
        printf(" - %d\n", identity(fb1).s[3]);

        return 0;
}

I just don't get it — it seems like all four groups should work exactly the same (aside from the extra " - 0" in the fourth one, which is only there to demonstrate that I do have a null byte there). Especially the second and third groups: how the heck could those differ from each other? (Obviously this is completely workaroundable, so it's not a big deal; but still, I'd like to understand what's going on!)

Thanks in advance for any thoughts. :-)

  • Post a new comment

    Error

    default userpic
  • 14 comments