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

The Ksplice blog is one of my all time favorite programming blogs. I am very happy it's back. If you haven't seen it before, it's well worth looking at the archive.

In question 2 I got tripped up because I assumed sizeof(int) == 8 on a 64 bit system. I also got question 4 wrong because I didn't know that &x gives a pointer to an array of size 5.



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).


The key is that "&" gives a pointer to the declared type. If you have a variable of array type (int x[100]), the pointer is to the array type (pointer to int[100]), not pointer to int.




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: