Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Arrays in C have always confused me a little, because books say "an array is just a pointer to the first element". Making matters even more confusing is that most C programmers first deal with arrays in the form of character buffers, which are logical arrays but are typed as pointers to the beginning of the string.

Also confusing was the first time I saw this wonderful construct:

    void f(int x){
        char buf[x + 1];
        printf("%zd\n", sizeof(buf))
    }
Not only does it work, it's also correct C99!

Writing C involves more care than usual because there are so many weird things that are easy to not understand, and not understanding those will cause subtle undefined behavior that allows people controlling the input data to 0wn your computer. Frightening.



I think you might be paraphrasing what the books say. What they usually say is that arrays and pointers are equivalent - which is true. It's easy to read that as saying that arrays and pointers are identical, but that's not true at all.

Just to make it confusing though, you can't pass an array by value to a function. It gets automatically converted to a pointer. Arrays are unique in the C language in this sense, and it contributes to the illusion that arrays and pointers are the same thing. (Try passing an array by reference, though, and all becomes clear.)


Nitpick: It should be %zu, not %zd (size_t is unsigned).




Consider applying for YC's Winter 2027 batch! Applications are open till November 2.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: