char arrays and memory allocation

My question is focused on the memory allocation of char arrays.

I know that with strings, the size of the string is dynamically allocated in the background via the string class.

But with char arrays, you have to explicitly assign the size of each char array (string). For example,

char a[20] = {....};

creates a space in memory that allocates enough size to hold a string of 20 characters. My specific question is this:

- If the user enters a string of less than 20 characters, does the array still take up the same amount of space (20 chars large)? More specifically, the memory size of the array doesn't decrease just because the user didn't enter 20 characters, right?
Last edited on
If the user enters a string of less than 20 characters, does the array still take up the same amount of space (20 chars large)?

Yes.

More specifically, the memory size of the array doesn't decrease just because the user didn't enter 20 characters, right?

Correct.
In C++, everything with a complete type has a fixed size. No exceptions. Except references. References don't have a size.

There is an operator named sizeof. Another way to remember the fixed-size rule is to remember that all occurrences of sizeof are constant expressions -- fixed forever at compile time.

(The sizeof a reference or a reference type is the size of the referenced type).
Last edited on
In C++, everything with a complete type has a fixed size. No Even exceptions.

Fixed. ;)
Topic archived. No new replies allowed.