-
June 17th, 2012, 12:19 AM
#1
REVERSE_of_STRING...
I keep getting segfaults when trying to run the code below. It seems Runtime error due to the line the *end = *begin; . Why is that?
#include <stdio.h>
#include <string.h>
void my_strrev(char* begin)
{
char temp;
char* end;
end = begin + strlen(begin)-1;
while(end>begin){
temp = *end;
*end = *begin;
*begin = temp;
end--;
begin++;
}
}
main()
{
char *string = "school";
my_strrev(string);
printf("%s", string);
}
TANUSHREE-AGRAWAL...
-
June 17th, 2012, 12:31 AM
#2
Re: REVERSE_of_STRING...
For your purposes, this is wrong:
Code:
char *string = "school";
It should be:
Code:
char string[] = "school";
Otherwise you have a pointer to the first element of a string literal, and you cannot modify that string literal.
By the way, please post code in [code][/code] bbcode tags.
-
June 17th, 2012, 06:49 AM
#3
Re: REVERSE_of_STRING...
Originally Posted by Tanushreeagr
I keep getting segfaults
What program written in Visual C++ segfaults?
Oh, you mean you're running this in Linux or some other OS and not using Visual C++? Then why did you post in the Visual C++ forum? Next time, post such questions in the Non Visual C++ forum.
If you did compile with Visual C++, the result should have been an unhandled exception (access violation). The reasons being the same as laserlight stated -- it is undefined behaviour to modify a string literal.
Regards,
Paul McKenzie
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|