change char* to '*'

I made a class:
1
2
3
4
5
6
7
8
9
10
class CMessage {
char* pMessage;
public:
void Reset() {
	char* temp = pMessage;
	while(*temp) {
		*(temp++) = '*';
	}
...
};


when I use the Reset method, all my CMessage object's memeber pMessage will be '*', I'm wonder why when I write this, it doesn't work, and output nothing:
1
2
3
4
void Reset() {
	while(*pMessage) {
		*(pMessage++) = '*';  // why this doesn't work??
}



and I also write these in
main()
just for test:
//test1
1
2
3
4
char* pMessage = "sharen";
char* temp = pMessage;
*temp = 'u';
cout << pMessage << endl;


//test2
1
2
3
4
5
char* pMessage = "sharen";
char* temp = pMessage;
while(*temp) {
	    *(temp++) = '*';
}

I think the test2 maybe work, but none of them work, they output nothing.

and when I write
char* pMessage = "sharen";
, the compiler says
deprecated conversion from string constant to 'char*' [-Wwrite-strings
, what should I do, just ignore it?
I will start from the last your complaint.:)

String literals in C++ have type const char []. So it will be more correctly to write
const char *pMessage = "sharen";

As for the code

1
2
3
4
void Reset() {
	while(*pMessage) {
		*(pMessage++) = '*';  // why this doesn't work??
}


I do not see where the memory was allocated that you are trying to fill in. Where does pMessage point?
Last edited on
if I write like this const char *pMessage = "sharen";, what if I want to change the pMessage?

for the code
1
2
3
4
void Reset() {
	while(*pMessage) {
		*(pMessage++) = '*';  // why this doesn't work??
} 


I don't totally understand what you say upper, could you explain to me more ? why have to make a temporary variable?

and why I write this in the main() function, it outputs nothing:
1
2
3
4
5
char* pMessage = "sharen";
char* temp = pMessage;
while(*temp) {
	    *(temp++) = '*';
} 


pMessage points to a string literal, which can't be modified. (Undefined behavious, usually a segfault because you're trying to write to read only memory)

Even if you create the pointer temp, it still points to the same non-modifiable memory.

To create the string as modifiable, make it an array:
1
2
char Message[] = "String";
char *pMessage = Message; //Create a pointer to the array 


Even better, use std::string and save yourself a lot of hassle:
 
std::string Message("String");
pMessage points to a string literal, which can't be modified.
why use a pointer can indirect modify it, like
1
2
3
4
5
void Reset() {
	char* temp = pMessage;
	while(*temp) {
		*(temp++) = '*';
	}
Your compiler might not be sticking it into ROM, it's undefined behavior. I guess I should have said "Not supposed to be modified".

If you want to create a pointer to a string literal you should always label it as const.
Topic archived. No new replies allowed.