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?
The 1st argument passed to the squeeze function is a read-only
string literal "hello"
, which you are trying to modify.
Instead pass it a modifiable char array:
char str[] = "hello";
printf("%s", squeeze(str, 'o'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With