Tutorial :C style char arrays - How many bytes do we store?



Question:

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?


Solution:1

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.


Solution:2

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


Solution:3

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.


Solution:4

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


Solution:5

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.


Solution:6

There are two ways to go when you need, e.g. 32 bytes, to store your data. The difference in these two versions:

// version 1  char *firstName = new char[32];    // version 2  char firstName[32];  

is that for version 1 the space your data allocated on the heap and you have to free before the program ends, whereas in version 2 the space is on the stack. Both will give you a variable that points to the first byte of your available space and this space is 32 bytes in both cases. People will argue that there are reasons why you might want to choose one over the other, but that is a different story.

sizeof( firstName )

The interesting point is what sizeof would return and this is the size of a char pointer (depends on your system and compiler) for version 1 and 32 for version 2. Keep in mind what another user mentioned, passing firstName to a function degrades it into a pointer.


Solution:7

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »