-
Reversing string
hi,
please see the code below:
void main()
{
int i,len;
char* str = "shalaka";
char temp;
len=strlen(str) - 1;
for(i=0;i<strlen(str)/2;i++)
{
temp = str[i];
str[i] = str[len];
str[len--]=temp;
}
}
str[i] = str[len]; => my program throws an exception at this line . Why?
Best Regards,
Shalak
-
I don't think you can change a string literal. Try making str an array instead of a pointer.
-
-
and
Code:
char str[] = "shalaka";
-
Ya, making "str" as an array works! But y does it not work with pointers?
-
*shrug* no idea, can't read code when there isn't code tags around it, perhaps edit the post and put in the code tags and repaste the code so there is formating.
-
The pointer points to a string literal, which is a constant that cannot be modified by the program (which is why you should be using const char* if you use a pointer). Using the array actually creates an array in memory and copies the contents of that string literal into the array. In that case it is yours to change however you'd like.
BTW, if you are using C++, you should probably be learning the C++ string class first instead of C style string like those that you are using.