Reputation: 25
I'm new to C. I'm trying to return a character pointer >> A pointer that points to a single character value. I know I can simply return a character but I want to learn how to return a character pointer pointing to a single character value.
char * returnPointerToCharacter(){
char s = 's';
char * pointerToS = &s;
return pointerToS;
}
int main()
{
// This code below works
char h = 'h';
char * pointerToH = &h;
printf("%c \n", *pointerToH);
// This code below doesn't work
char * pointerToS = returnPointerToCharacter();
printf("%c \n", *pointerToS);
return 0;
}
Upvotes: 0
Views: 65
Reputation: 180113
I'm trying to return a character pointer
Your code does return a character pointer. But it also commits a cardinal sin: it returns a pointer to an object whose lifetime ends with the completion of the function call. The resulting pointer is therefore useless to caller.
There are several alternatives. Often, if one is going to return a pointer, one dynamically allocates the object to which it is to point. Dynamically allocated objects live until they are explicitly freed. For your particular purposes, however, I would suggest making the function's local variable static
, which exactly means that it lives and retains its last-set value for the entire life of the program:
char * returnPointerToCharacter(){
static char s = 's';
return &s;
}
Upvotes: 0
Reputation: 854
The problem is that char s is on the stack, and gets popped from the stack, so you're returning a pointer to a destructed element.
If you just want a function that returns a char pointer, you could try something simple:
char * returnPointerToCharacter(char *s){
return s;
}
...// Do stuff
char f;
char * pointerToS = returnPointerToCharacter(&f);
Upvotes: 1