0

I'm trying to write a function that returns a pointer to an array and I'm very confused as to what the "static" keyword is doing. For instance, this function doesn't work:

int* doesnt_work() {
    int r[] = {43, 67};
    return r;
}

And I've seen people recommending just putting the "static" keyword before the array:

int* works_static() {
    static int r[] = {43, 67};
    return r;
}

But I found out that I could do the same thing by declaring a pointer in the function, point it to the array, and then return the new pointer instead of the name of the array:

int* works_newPtr() {
    int r[] = {43, 67};
    int* p = r;
    return p;
}

What exactly is the keyword "static" doing in this case and why is the doesnt_work() function not working while the works_newPtr() is doing fine?

  • Remember that just because something appears to work doesn't mean it actually works. – eesiraed Mar 14 '20 at 18:33
  • 1
    `works_newPtr` also doesn't work. – Eljay Mar 14 '20 at 18:33
  • Read about the scope of automatic variables (their lifetime ends when the method terminates its execution). – gsamaras Mar 14 '20 at 18:33
  • Sorry, but what you think works, doesn't. It only makes [demons fly out of your nose](http://www.catb.org/jargon/html/N/nasal-demons.html), because it's returning a pointer to a destroyed object. See the duplicate question for a detailed rundown on what `static` means. – Sam Varshavchik Mar 14 '20 at 18:36

0 Answers0