views:

68

answers:

6
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?

+5  A: 

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.

James Curran
+1  A: 

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.

Thomas
+1  A: 

It occupies exactly 32 bytes of memory.Internally everything an address.Variables are only for our understanding.

chaitanyavarma
A: 

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.

schoetbi
If it's not dynamically allocated, there are no ints on the stack. The address is known at compile-time, so it doesn't need to be stored.
siride
Why would there be any need to store the address on the stack? Nor would that be an `int`, if it existed, but rather a `char *`, which is not necessarily the same thing.
David Thornley
There is no extra int.
5ound
Sorry for my english I had the dynamic case in mind when I entered probably.
schoetbi
+1  A: 

That takes up 32 bytes. It will hold a 31-character string (the other byte is for the null string terminator).

David Thornley
I'd say *can* hold a "31-character null terminated string". It doesn't have to be null-terminated, or even a string.
GMan
A: 

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.

dauphic
It's not necessarily on the stack. It could be a global. It could be part of a struct.
James Curran