char firstName[32];
I understand that each char occupies 1 byte in memory. So does the above occupy 32 bytes of memory?
Am I missing a pointer that takes up memory too or is this just 32 bytes?
char firstName[32];
I understand that each char occupies 1 byte in memory. So does the above occupy 32 bytes of memory?
Am I missing a pointer that takes up memory too or is this just 32 bytes?
No, that takes up exactly 32 bytes of memory. There is no pointer.
This is often an area of confusion, since an array name silently "decays" to a "char*"
char* fname = firstName;
So, firstName
may be of type const char*
, but it is not itself a char* variable. It is exactly like:
int x = 5;
x
is int variable and takes up space. 5
on the other hand, is just a constant value of int type. It takes of no space; it's just a value.
This is just 32 bytes. The name of the array sometimes acts like a pointer to the first element, but it is not a pointer.
It occupies exactly 32 bytes of memory.Internally everything an address.Variables are only for our understanding.
In the debug version there are also bytes stored beyond the array (on some compilers) to check for writing after the array. In the release version it should be 32 bytes plus one int on the stack (probably) to store the address.
That takes up 32 bytes. It will hold a 31-character string (the other byte is for the null string terminator).
The statement char firstName[32]
creates an array of 32 characters, or 32 bytes, on the stack. Because it's on the stack, the compiler knows exactly where it is in relation to the stack pointer. The compiler will hardcode the address of the array into any operations that use it; there's no need for storing a pointer to it.
It's important to note that if you attempt to pass this array as a function argument, it will degrade into a pointer to the array, because C++ doesn't allow passing primitive arrays by value. Most people who are new to C++ would expect it to pass a copy of the array.