char array vs string array, why?

The Partridge Family were neither partridges nor a family. Discuss.
Post Reply
Natox
Posts: 51
Joined: January 10th, 2012, 2:51 pm
Location: the Netherlands
Contact:

char array vs string array, why?

Post by Natox » February 3rd, 2012, 4:37 pm

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!
My Weblog: http://www.gamer-bay.com/
Keep track of my learning progress on the C++ programming language.

User avatar
chili
Site Admin
Posts: 3948
Joined: December 31st, 2011, 4:53 pm
Location: Japan
Contact:

Re: char array vs string array, why?

Post by chili » February 4th, 2012, 3:13 am

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.
Chili

Natox
Posts: 51
Joined: January 10th, 2012, 2:51 pm
Location: the Netherlands
Contact:

Re: char array vs string array, why?

Post by Natox » February 7th, 2012, 10:26 am

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
My Weblog: http://www.gamer-bay.com/
Keep track of my learning progress on the C++ programming language.

Post Reply