Page 1 of 1

char array vs string array, why?

Posted: February 3rd, 2012, 4:37 pm
by Natox
Hi chili, I have a question for you.
I've been studying arrays of several kinds, but I keep asking myself the following question:
"Why (besides from the fact that you can call single characters) would you ever use 'char' arrays instead of 'string' arrays?

I mean for instance:

char myArray[4] = {'H','E','Y','\0'};
string myArray[1] = {"HEY"};

What is the difference in pratice? And why would you prefer one over another?

Cheers!

Re: char array vs string array, why?

Posted: February 4th, 2012, 3:13 am
by chili
Hmmm... a char array is a string. :?

I think you have some confusion about the word "string". A string is just an array of characters. In C, a string is indicated by an array of characters wherein the final character is the 'null' character ('\0') which is used to indicate the end of the string.

There is also a string object in the STL (Standard Template Library). It is an object which encapsulates a string and provides methods and operators to make it a lot easier to work with strings.

Therefore, an array of chars constitutes one string, and an array of string objects is a list of a plurality of strings.

A better question to ask would be: what is the advantage of using C-style strings (null terminated strings) vs the STL string object.

Short answer: simple null terminated strings are simpler, faster, and contribute to a smaller executable file than if you use the string object. But generally it's a bigger hassle to work with naked C-style strings, so the string object is very handy. And the difference in speed/executable size shouldn't be that big of a deal either way. Still, you should be able to work with both, and I will likely be using both in my videos.

Re: char array vs string array, why?

Posted: February 7th, 2012, 10:26 am
by Natox
Thanks for the clear answer mate.
I always thought a string was yet another variable type.... but now I understand!
Now I do understand what C-Style strings are too... that used to be confusing aswell!

Thanks, thanks, thanks