繁体   English   中英

c函数指针的返回值

[英]c function pointer return value

所以当我尝试这样做的时候,我在玩c的时候很开心:

#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);
}

显然,我不能将指针(用作参数)用作指针函数的返回值。

好吧,有人可以解释这种行为吗? 我如何获得void函数的返回值?

所以我在写问题时找到了解决方案。

显然,char指针实际上并不是某种意义上的指针。 当我意识到这一点时,它尝试使用指向指针(**)的指针来代替,并且成功了。

#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);
}

在原始代码中:

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

message = "DONE"; 将更改名为message局部 (或“自动”)变量,因为从所有意图和目的来看,函数参数都是C中的局部变量。

因此,来自mainmessage局部变量的值将不会更改,因为这是两个不同的变量。

现在,在第二个示例中,您将指针传递给指针:

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

因此,您的*message = "DONE"; 现在正在更改message (参数)指向的内容,并且它指向来自main()message ,因此它正在更改来自main() message 来自helloWorld()本身的message此处未更改。

当然,字符指针与其他指针没有什么特殊之处,它们与其他指针一样多。 唯一的特别之处是将字符串文字当作字符指针,但这并不重要。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM