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;
}
精彩评论