Hacker News new | ask | show | jobs
by icedchai 3461 days ago
Interesting. I've been working with C for almost 30 years (first taught it to myself when I was 14) and never thought about the actual type of array.
2 comments

You're not alone. I've been programming in either C or C++ for 25 years, and it wouldn't have occurred to me that you can have a "pointer to array of size N" that includes the size. Though I probably could have been led there with a little Socratic questioning.
The reason why people don't usually run into this is because C tries really hard to decay your arrays to pointers to first element, so there are very few cases where it actually comes up - sizeof(array) and &array are some of the few. On top of that, writing down the type of such an array is not exactly obvious, and requires parentheses:

    int (*p)[10];
This all is much more interesting in C++, because there, in conjunction with references, this lets you write functions that take arrays as arguments and know their length. Like so:

    template<size_t N>
    void foo(const int (&a)[N]) {
        for (size_t i = 0; i < N; ++i)
            cout << a[i];
    }

    int a[10];
    foo(a);
If you start thinking about two dimensional arrays, you'll probably get close quickly.
Which kind of explains so much about the problem with C. ;-)
I think it more explains that you can do a lot without fully understanding what it is you are working with.

Which can be good or bad.

I think the important irony that perhaps wasn't plainly obvious in my statement is that C is often cited by programmers as a preferred tool (particularly over Java or C++) because they "know exactly what is going on with each line of code". ;-)
> I think it more explains that you can do a lot without fully understanding what it is you are working with.

That's the same thing I'm saying. :-)