tags:

views:

97

answers:

4
char* fun(char *s) {
  char buffer[50];
  int i=0;
  while(*s){
    if(isdigit(*s)){
      buffer[i++]=*s;
    }
    s++;
  }

  buffer[i]='\0';
  return buffer;
}

int main(){
  char *s="o34";
  char *p="off";

  p=fun(s);
  while(*p){
    printf("%c",p);
    p++;
  }
  //printf("%s",fun(&s[0]));
  //puts(fun(s));
  getchar();
}
+2  A: 

Two problems:

  • You are returning a pointer to the character array that is local to the function.
  • In printf("%c",p); it should be *p
codaddict
A: 

One immediate problem I see is that you return a temporary buffer from fun. This causes undefined behavior. Better pass the buffer to the function or use some heap allocation (and do not forget to free it later in main).

dark_charlie
A: 

You're returning the address of a local array:

char* fun(char *s){
  char buffer[50]; 
  ...
  return buffer;
}
Samuel_xL
A: 

Declare the buffer as static to remove the short-term problem, but after calling the function a second time, the first reference will no longer have the old contents -- it will still point to the new contents of the buffer.