Why does this program give segmentation fault?
It's a beginners question: Why is this breaking/giving an error?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *strtrim_right(char *p)
{
char *end;
int len;
len = strlen( p);
while (*p && len)
{
end = p + len-1;
if(isalpha(*end))
*end =0;
else
break;
}
return(p);
}
int main ()
{
char *x="PM123BFD";
strtrim_right开发者_如何转开发(x);
printf("%s", x);
return 0;
}
Change
char *x="PM123BFD";
to
char x[]="PM123BFD";
You cannot modify a string literal, so instead pass the function a char
array which it can modify.
I don’t see why it should break – I would rather expect an infinite loop: the while
condition will always be true and the loop will never be left.
Rework the loop condition, it’s borked. Then look at the variables you have: you never change the values of either p
or len
. This isn’t right. Furthermore, the code inside the loop is much more complicated than need be. Think about whether you really need three variables here.
Ok thanks to the 2 answers above here is what seems to be ok now:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *strtrim_right(char *p)
{
char *end;
int len;
len = strlen( p);
while (*p && len)
{
end = p + len-1;
if(isalpha(*end))
*end =0;
else
break;
len = strlen(p);
}
return(p);
}
int main ()
{
char x[]="PM123BFD";
strtrim_right(x);
printf("%s", x);
return 0;
}
精彩评论