0

Ok - so i'm learning C - specifically for this question pointers and functions.

I have this function

char *RemoveVowels(char *str) {

char outStr[40];
for (size_t i = 0; i < sizeof(outStr); i++)
    outStr[i] = '\0';

char *c = outStr;

while (*str) {
    switch (*str)
    {
    case 'A':case'a':
    case 'E':case'e':
    case 'I':case'i':
    case 'O':case'o':
    case 'U':case'u': 
        *str++;
        break;
    default:
        *c++ = *str++;
        break;
    }
}
*c = '\0';
return outStr;
}

I'm just trying to get my head around how pointers play with arrays and how they are used to return strings.

When i call this function with

puts(RemoveVowels("some string with vowels in it"));

The function works, i'm not concerned with better ways to do it, i'm sure there are, it's the pointer/array/string manipulation that i'm interested in.

I can see the string has created a new string and removed the vowels in outStr. However i just get gibberish from puts(), why doesn't the string get printed, i ensured it ended with the NULL?

Be gentle i'm learning :)

Sean Smith
  • 181
  • 1
  • 12
  • 2
    Returning the address of a local variable is going to make trouble. – Yunnosch Jun 17 '18 at 19:14
  • You are getting segmentation fault with this. You can easily put static in front of `char outStr[40];`. This will solve your problem because lifetime of a variable is extended to the lifetime of a program. – NutCracker Jun 17 '18 at 19:15

1 Answers1

1

You return the address of the local variable outStr.
This alone is a reason to change, the reason is called undefined behaviour and should ring all alarm bells.
Here is one speculation of which nasal demons exactly are flying around. This is not an explanation of what happens in your case, just one idea to scare you off.

After returning the address of a local variable in one function (RemoveVowels()) you then call another function (puts()), which surely has its own local variables.
You have to assume that the local variables of that function are created in the same place as the local variables of the previous function were, i.e. everyting is killed and overwritten.
So whatever the first function did in its now non-existing local variables is lost.
There is nothing you can expect.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54