Jacques Labuschagne wrote:
jose luis fernandez diaz wrote:
Hi,
In the program below:
#include <iostream.h>
#include <set>
int main()
{
const char *ptr_vars[] = {"one"};
const set<const char *> vars_art(ptr_vars,
ptr_vars+sizeof(ptr_vars)/sizeof(*ptr_v
ars));
char *ptr = "one";
char buffer[100];
strcpy(buffer, "one");
cout << vars_art.count(ptr) << endl;
cout << vars_art.count("one") << endl;
cout << vars_art.count(buffer) << endl;
}
Why "vars_art.count(buffer)== 0" ?
Because the literal "one" doesn't live in the same memory location as
buffer. It has the same data, but the pointer value is different (and
that's what you're comparing).
To elaborate, the line
strcpy(buffer, "one");
copies the data { 'o', 'n', 'e', '\0' } into buffer. The literal "one"
still exists as a seperate string; you now have two copies of that
data. The set stores pointer values. When it counts occurrences it
looks at the value of the pointer, NOT the value of the thing being
pointed to.
HTH,
Jacques.