开发者

print only number,why it output so weird? [closed]

开发者 https://www.devze.com 2023-01-21 13:00 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.开发者_开发问答 Closed 12 years ago.
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();
}


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


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.


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).


You're returning the address of a local array:

char* fun(char *s){
  char buffer[50]; 
  ...
  return buffer;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消