user4793626
user4793626

Reputation:

c function pointer return value

So I was having some fun with c when I tried this:

#include <stdio.h>
#include <string.h>

typedef void (*Function)(char *);

void helloWorld(char *);
void execute(Function, char *);

Function func;

int main(void){
    char *message = "StackOverflow";
    execute(helloWorld, message);

    printf("%s", message);
    return 0;
}

void helloWorld(char *message){
    printf("HelloWorld, %s.\n", message);
    message = "DONE";
    printf("[%s]\n", message);
}

void execute(Function function, char * msg){
    func = function;
    func(msg);
}

Apparently I am not able to use pointers - which I used as parameter - as return value of pointer functions.

Well, can someone explain this behavior? How can I get return value(s) of void function?

Upvotes: 0

Views: 870

Answers (2)

srdjan.veljkovic
srdjan.veljkovic

Reputation: 2548

In your original code:

void helloWorld(char *message){
    printf("HelloWorld, %s.\n", message);
    message = "DONE";
    printf("[%s]\n", message);
}

the line message = "DONE"; will change the local (or "automatic") variable named message, because function parameters are, for all intents and purposes, local variables in C.

Thus, the value of the message local variable from main will not change, as those are two different variables.

Now, in your second example, you are passing pointers to pointers:

void helloWorld(char **message){
    printf("HelloWorld, %s.\n", *message);
    *message = "DONE";
    printf("[%s]\n", *message);
}

So, your *message = "DONE"; is now changing what the message (parameter) points to, and it is pointing to the message from main(), thus it is changing message from main(). The message from helloWorld() itself is not changed here.

Of course, there is nothing special about character pointers w.r.t other pointers, they are pointers as much as any other. The only special thing is treating string literals as character pointers, but that doesn't matter here.

Upvotes: 0

user4793626
user4793626

Reputation:

So I found a solution while writing the question.

Apparently char pointers are not actually pointers, somehow. When I realised this it tried using pointer to pointer (**) instead and it worked.

#include <stdio.h>
#include <string.h>

typedef void (*Function)(char **);

void helloWorld(char **);
void execute(Function, char **);

Function func;

int main(void){
    char *message = "StackOverflow";
    execute(helloWorld, &message);

    printf("%s\n", message);

    return 0;
}

void helloWorld(char **message){
    printf("HelloWorld, %s.\n", *message);
    *message = "DONE";
    printf("[%s]\n", *message);
}

void execute(Function function, char ** msg){
    func = function;
    func(msg);
}

Upvotes: 1

Related Questions