views:

143

answers:

3

Hi, 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;
}  
+4  A: 

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.

Konrad Rudolph
+10  A: 

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.

codaddict
A: 

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;
}  
francogrex
why is strtrim_right returning a char pointer if you aren't using it?
jmtd
@francogrex: there’s still a lot wrong with this code. The `while` condition and the code inside the loop are still hopelessly complicated.
Konrad Rudolph
@jmtd: right, this return should be removed.
francogrex
void strtrim_right(char *p) { p += strlen(p) - 1; while(isalpha(*p)) { *p-- = 0; } }
jmtd