incrementing char pointers

Dec 23, 2011 at 5:56pm
hello,
I was playing around with char pointers. I wanted to increment each letter of a char array by 1 character. i.e. 'hello' becomes 'ifmmp' (i = h+1)and here is a small code i wrote :


char *rushil = "hello";

while(*rushil != '\0')
{
++(*rushil); // run time error in this line dev C++ crashes
rushil++;
}

i am not sure but the program hangs on the line ++(*rushil).
I also tried :

*rushil = *rushil +sizeof(char); but error again

please help in terms of logic.
Thank you
Dec 23, 2011 at 6:12pm
You are trying to change a constant char string. You need to define the string in writable memory in order to edit it.

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

int main()
{
	char buffer[16] = "hello";
	char *cstr = new char[16];
	memcpy(cstr, buffer, 16);
	char *p = cstr;

	while (*p != '\0')
	{
		++(*p);
		++p;
	}

	std::cout << cstr << std::endl;
	delete[] cstr;
}

Dec 24, 2011 at 4:44pm
oh.. ok.

but doesn't the char pointer (in my code) point to a fixed address and the value stored in the address can change?
Thanks,
-Rushil
Dec 24, 2011 at 4:54pm
and the value stored in the address can change?

You can't change it, because string literals are constant as wolfgang already said (that means they can be in memory sections that are read-only).

Conversion to a pointer to non-const char is only allowed for compatibility reasons and your compiler should warn you about it ("warning: deprecated conversion from string constant to ‘char*’"). Trying to modify the string results in undefined behavior.
Dec 24, 2011 at 4:59pm
In your code the string is likely to be stored in 'read only' memory that will throw a memory protection fault if you attempt to change it.

Also you might consider using std::string instead:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <string>
#include <iostream>

int main()
{
	std::string rushil = "hello";

	for(size_t i = 0; i < rushil.length(); ++i)
	{
	    ++rushil[i];
	}

	std::cout << rushil << '\n';
}
Last edited on Dec 24, 2011 at 5:00pm
Dec 27, 2011 at 7:24pm
ohh... ok.. thank you all for ur help.. i think i understand..
Topic archived. No new replies allowed.