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();
}
views:
97answers:
4
+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
2010-10-19 15:41:43
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
2010-10-19 15:42:46
A:
You're returning the address of a local array:
char* fun(char *s){
char buffer[50];
...
return buffer;
}
Samuel_xL
2010-10-19 15:43:14