Search This Blog

Monday, April 12, 2010

Return a pointer to a char array in C

Programmer Question

I've seen a lot of questions on that on StackOverflow, but reading the answers did not clear that up for me, probably because I'm a total newbie in C programming. Here's the code:



#include <stdio.h>

char* squeeze(char s[], char c);

main()
{
printf("%s", squeeze("hello", 'o'));
}

char* squeeze(char s[], char c)
{
int i, j;

for(i = j = 0; s[i] != '\0'; i++)
if(s[i] != c)
s[j++] = s[i];
s[j] = '\0';

return s;
}


It compiles and I get segmentation fault when I run it. I've read this faq about about returning arrays and tried the 'static' technique that is suggested there, but still could not get the program working. Could anyone point out exactly what's wrong with it and what should I be paying attention in the future?



Find the answer here

No comments:

Post a Comment

Related Posts with Thumbnails