Well, firstly, you are missing the "case" declaration in the switch statement, as well as the breaks at the end of the statement. Try changing the code:
char* f(int i) { int i; char buffer[20]; switch ( i ) { case 1: strcpy( buffer, "string1"); break; case 2: strcpy( buffer, "string2"); break; case 3: strcpy( buffer, "string3"); break; default: strcpy(buffer, "defaultstring"); break; } return buffer; }
In addition, you override your parameter i local variable named i . Therefore remove this:
char* f(int i) { char buffer[20]; switch ( i ) { case 1: strcpy( buffer, "string1"); break; case 2: strcpy( buffer, "string2"); break; case 3: strcpy( buffer, "string3"); break; default: strcpy(buffer, "defaultstring"); break; } return buffer; }
Finally, you return a char pointer that points to a local statically declared character array called buffer . buffer drops out of scope as soon as a pointer returns to its first element (which is what your return statement does). This means that you get a pointer to a variable that no longer exists. To fix this, you can pass a pointer to a buffer in a function, for example:
void f(char *buffer, int i) { switch ( i ) { case 1: strcpy( buffer, "string1"); break; case 2: strcpy( buffer, "string2"); break; case 3: strcpy( buffer, "string3"); break; default: strcpy(buffer, "defaultstring"); break; } }
This latest version should work if you make sure buffer is long enough to accept a string. If you really want to make it safe, take the length of the buffer and check that against the length of the string that you are copying.