Well, for one thing, you're missing the 'case' declaration in your switch statement as well as the breaks at the end of the statement. Try changing your code to this:
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;
}
Also, you're overriding your parameter i
with a local variable named i
. So remove that:
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 are returning a char pointer that points to a local statically declared character array named buffer
. buffer
falls out of scope as soon as the pointer to its first element is returned (what your return statement does). What that means is you end up with a pointer to a variable that no longer exists. To fix this, you can pass a pointer to buffer into the function, like this:
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;
}
}
That last version should work, provided you make sure that buffer
is long enough to accept the string. If you really want to make it safe, take in buffer
's length as well and check that against the length of the string you are copying.