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

26,139

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

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 4

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 5

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

Share:
26,139
Admin
Author by

Admin

Updated on September 08, 2021

Comments

  • Admin
    Admin over 2 years
    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?