Re: [OT] An array of C-Strings
Re: [OT] An array of C-Strings
- Subject: Re: [OT] An array of C-Strings
- From: David Phillip Oster <email@hidden>
- Date: Sat, 26 Jan 2002 21:20:10 -0800
In practise, you need to worry about storage leaks, and you'll be wanting
multiple strings, not identical copies of the same string. A better example
is:
#include <vector>
#include <string>
#include <vector>
#include <iostream>
int main(void){
std::vector<std::string> days;
char *word = "The length of the word would be variable";
/* example with each element the same string (implicit conversion) */
for(int i = 0; i < 7; ++i){
days.push_back(word);
}
/* example with each element a different string */
for(int i = 0; i < 7; ++i){
days.push_back(std::string(word, std::strlen(word) - i));
}
for(int i = 0; i < days.size(); ++i){
std::cout << days[i] << std::endl;
}
return 0;
}
(I tested it before posting)
because it uses std::string, which is designed to be treated as a value,
and designed to hold variable length string data.
Unlike Objective-C, a std::vector doesn't retain its elements, and doesn't
destroy pointers when it is deallocated. Instead, it expects elements with
copy semantics, and does send a "delete" to them when the vector is
deleted. std::string, not char *, has the correct semantics to be an
element of a vector.
I can't recommend a _single_ C++ book, but I can recommend a pair:
Start with "Accelerated C++" by Koenig&Moo, and immediately follow it with
"Exceptional C++' by Herb Sutter. If you stop after the first book, your
code will be full of errors when the libraries throw exceptions. The second
book will teach you how to code correctly, even if the libraries throw
exceptions.
--
David Phillip Oster
<
mailto:email@hidden>