A Some What Decent Head Spiner

I have had quite a head spinner on trying to transform a string into a char. I've been trying to do this for the project below.
http://www.codeproject.com/Articles/35374/Two-Efficient-Classes-for-RC-and-Base-Stream-Ci#_comments
1
2
3
	std::string str = "string";
	const char* chr = str.c_str();
	cout << *chr << endl;

Above is the code I have tried using and it stores data under *chr, it however only stores one letter rather than the entire word like for example string.
Well, you only print the character it points to(*chr e.g. the first character of the string) instead of the cstring(chr)

That should do the trick
cout << chr << endl;

Notes:
- chr is a pointer to a char (see decleration)
- *chr gives you the value the pointer points to.

std::cout knows that a char* should be a cstring and prints characters until the pointer points to the end-of-string character (0 || '\0')

by just giving him a character (the value chr points to) it just prints the character

I'll just throw a piece of code here for a better understanding of my imcompetent english skills

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

int main()
{
	char* Array = new char(3);

	Array[0] = 'G';
	Array[1] = 'g';
	Array[2] = 0;

	std::cout << *Array << std::endl;
	std::cout << Array[0] << std::endl;

	std::cout << *(Array+1) << std::endl;
	std::cout << Array[1] << std::endl;

	std::cout << Array << std::endl;

	return 0;
}

1
2
3
4
5
6
output:
G
G
g
g
Gg
Last edited on
No, it doesn't.

The chr is a pointer. The pointer stores an address. Dereferencing a pointer returns the value from an address.

The *chr is same as *(chr+) is same as chr[0]. That is one character. It is not "stored by chr". The chr has an address that was returned by the str.c_str().

Now you should read the documentation of all the methods of std::string to learn which of them can or will invalidate all iterators, references, and pointers to strings' data. If you use any of those, the chr will still have the same address, but it will no longer be the address of the string that the str stores.

If you do need a deep copy, then you have to allocate memory for that copy.
Topic archived. No new replies allowed.