char vs string

Hi everyone!

I am teaching myself C++. I would like to know what are the efficiency differences between using arrays of chars and strings. According to the book I am following, using arrays of chars is "an efficient way to store strings, provided that few strings need to be removed." Can somebody explain it to me, please?

Second question: a char type has size of 1 bite while a string type has size of 8 bites. I can use a variable of string type to store a 30-letter word (30 characters) however if I use an array of chars to store the same 30-letter word, it will occupy 30 bites, right? Which under this logic, it seems that using arrays for storing strings is less efficient in terms of memory, right?



Usually when bringing up "efficiency", people talk about the time it takes to execute a program. Strings and arrays of char (and vectors of char) are the same in that regard.

However, for the "efficient way to store", that is, minimizing memory footprint, arrays are indeed better: a string holding the same number of characters occupies more memory than an array: each string object has to maintain the pointers and other information about the array it owns (those "8 bytes" you saw in your case), although that is somewhat mitigated by small string optimization, and the array itself is usually larger than necessary (print out string.capacity() in your test)
Last edited on
Many thanks Cubbi!
Topic archived. No new replies allowed.