Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a pointer to a char array in C

Tags:

arrays

c

chars

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?

like image 663
snitko Avatar asked Apr 13 '10 02:04

snitko


1 Answers

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'));
like image 85
codaddict Avatar answered Sep 20 '22 23:09

codaddict