After reading the faq’s and everything else I can find, I’m still confused. If I have a char pointer that is initialised in this fashion:
char *s = 'Hello world!'
The string is in read-only memory and I cannot change it like this:
*s = 'W';
to make ‘Wello world!’. This I understand, but I can’t, for the life of me, understand how to make it NOT read-only. Do I have to use an array instead of a pointer? Like here?
This is my code:
char *s = str; char *e = s; while (*e != '\0') e++; e--; char *temp; //Swop the string around while (s <= e) { *temp = *s; *s = *e; *e = *temp; e--; s++; }
The error message is just a segmentation fault. Apologies in advance if this is a really stupid question.
Thanks so much for all the help. After taking all your advice, I get this:
void something(char * str) { char *store = str; char *s = new char[strlen(str) + 1]; //Allocate memory. Nice one. strcpy(s, str); char *e = new char[strlen(str) + 1]; strcpy(e, str); while (*e != '\0') e++; e--; char temp; //no longer a pointer while (s <= e) { cout << *e; temp = *s; *s = *e; *e = temp; e--; s++; } delete [] e; delete [] s; }
however, the deletes at the end of the function seem to be causing their own segmentation faults. Why?
For interest’s sake: The faults were due to accessing the e and s pointers after they were incremented. A much simpler solution followed from that:
void something(char * str) { char *s = new char[strlen(str) + 1]; strcpy(s, str); char temp; int j = strlen(str) - 1; for (int i = 0; i <= strlen(str)/2; i++) { cout << s << endl; temp = s[i]; s[i] = s[j]; s[j] = temp; j--; } delete [] s; }
The easiest way to modify it is to create an array for your storage, and then copy the string into it.
For example:
The reason your code doesn’t work is that you haven’t allocated any memory for the copy of the string – you’ve just made a second pointer to the same read-only memory. (And then tried to copy it? I’m not quite sure what the rest of the code is doing.) You need to get some non-read-only memory somewhere, and it’s much easier to use the standard library to copy it into that new memory, rather than writing the loop yourself.
In the case when you don’t know the length of the string beforehand, you can also use malloc (or, even better, do what drschnz’s answer says and use new char[]):
Also, if you’re using C++, you can just use a std::string:
Hope that helps.