title: Returning strings in C. Why is this working?
body: <p>Sorry if something similar has been posted here already, but I couldn't really find it.</p>
  
  <p>I have the following code and, even though I would say this is not correct, I receive the right answer.</p>
  
  <pre><code>char *selectStr(int index){
      char *str[] = {
          "hello",
          "hola",
          "epa",
          "alright",
      };
      return str[index];
  }
  
  int main() {
      printf("String: %s\n", selectStr(2));
      return 0;
  }
  </code></pre>
  
  <p>Can anybody tell me why this actually works? The way I see it: an array of strings <code>str</code> is a local variable inside the selectStr function. This function returns a string contained inside this array. But since this array of strings <code>str</code> is a local variable, it should be cleaned from memory after it returns (right?), so I was expecting to get some sort of a memory access error.</p>
  
  <p>Should I consider myself lucky that this code works (i.e. is this an undefined behavior?) or this is actually a good way of doing things (in this case, why)?</p>
  
  <p>My guess is that the pointer to the array <code>str</code> gets cleaned after the function returns, but not the actual content that it points to, which stays in memory until something else writes on it. I would really appreciate if somebody could confirm that, or else, tell me what is actually going on.</p>
  
  <p>Thanks in advance!</p>
  
  <p>PS: The way I would do it is to pass a buffer as a parameter, but I'm just curious to know why, surprisingly --at least for me--, this actually works.</p>