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;
}  
3
  • 2
    What error? What line? What compiler? What platform? How do you expect we help you if you don't provide information? Commented Sep 17, 2010 at 12:00
  • 1
    "deprecated conversion from string constant to ‘char*’" for x; rather use a char array: char x[] = ... Commented Sep 17, 2010 at 12:19
  • 1
    The standard answer: because you invoked undefined behavior. :-) Commented Sep 17, 2010 at 17:04

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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;
}  

3 Comments

why is strtrim_right returning a char pointer if you aren't using it?
there’s still a lot wrong with this code. The while condition and the code inside the loop are still hopelessly complicated.
void strtrim_right(char *p) { p += strlen(p) - 1; while(isalpha(*p)) { *p-- = 0; } }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.