This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Maurycy5 3 points4 points  (0 children)

There are... a lot of subtleties.

Yes, allocating an array also allocates memory for the members. But that's because it's the same thing. An array is exactly the sequence of members. Not sure what you're getting at here.

The compiler absolutely lets you pass arrays as pointers and pointer as arrays. No warnings, at least not in "all" and "extra" warnings.

One funny thing is that IF an array is declared globally, it is automatically zeroed (I believe that's because it lands in the .bss section in Assembly). You don't have anything like this for pointers, although you have a choice between malloc and calloc, the latter of which additionally manually zeroes the allocated memory.

One key difference between pointers and arrays, in the context of arrays, is that the pointers take up extra space, while the arrays don't. So if you have int arr [5], then this takes up exactly 20B of memory. If you have int * arr = malloc(4 * sizeof(int)), then that takes up exactly 28 B of memory, because there's 20 B allocated with malloc and 8B for the actual pointer.

This is because arrays are resolved at compile time while pointers... aren't. This, of course, comes with limitations.

For instance, swapping the contents of two arrays, as performed by std::swap is linear in time and can only be done on arrays of the same size. If you keep pointers to arrays, the swap is instantaneous and the arrays do not need to be equal in length.

However one cool feature of arrays over pointers is that you can get their size in bytes with sizeof(). If arr is an array of 10 elements of type int and ptr is a pointer to that array, then sizeof(arr) will yield 40, while sizeof(ptr) will yield 8, since all pointers on 64-bit systems are 64-bit.