cpp_is_king
Member
I thought there was a way to identify the number of elements in a C array through the application of sizeof. It's one of the few instances where there's a difference when defining a a variable as an array type instead of as a pointer.
Something like
Code:int a[5]; printf("a has %d elementsn", sizeof(a) / sizeof(a[0]));
Just an academic question. In practice you're usually either going to dynamically allocate arrays into a pointer variable or set the array size using a constant, which you can just reuse.
At the lowest level, an array is not even a thing in c++ (ignoring std::array for the sake of this discussion). Blocks of memory are a thing though. What you've got there is a block of memory of either 20 or 40 bytes depending on your platform. The rest is syntactic sugar to help the compiler figure out how to interpret the bytes.
So in one sense, ok you can think of it as an array of 5 ints. But if I write this:
Code:
void foo(int *array)
{
}
int main(int argc, char **argv)
{
int a[5];
foo(a);
}
Inside the body of foo, there's no way to know how "big" this array is. Because an array is just a pointer.
By convention, people frequently treat these statically allocated arrays as being of a constant size, and using the technique you just demonstrated to determine its size.
But in CornBurrito's post, he wanted to know specifically how to "change the size". And my point is just: The size is what you say it is, as long as there is enough memory.
If it had 5 elements and you want it to have 4 elements, just start telling people who use it that it has 4 elements. Done.
If it has 4 elements and you want it to have 5, tell people it has 5 (as long as its buffer is large enough to actually hold 5 values)
In his example where he said he didn't know what to do about the last item in the list, the answer is: it doesn't matter. Because you're going to tell people the list has 4 items, and so they won't even bother to look at the 5th.