2

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;
}  
codaddict
  • 445,704
  • 82
  • 492
  • 529
francogrex
  • 465
  • 1
  • 4
  • 17

3 Answers3

11

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
  • 445,704
  • 82
  • 492
  • 529
5

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
  • 530,221
  • 131
  • 937
  • 1,214
0

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;
}  
codaddict
  • 445,704
  • 82
  • 492
  • 529
francogrex
  • 465
  • 1
  • 4
  • 17