gpt4 book ai didi

c - 在 C 中处理多个函数中的指针

转载 作者:行者123 更新时间:2023-11-30 14:28:44 25 4
gpt4 key购买 nike

我正在尝试从现有代码中创建函数以使其更清晰,但我遇到了一些问题:

以前是:

int foo(char * s, char * t, char ** out) {
int val = strcmp(s, t);
if (val == 0) {
*out = strdup(s);
return 1;
} else {
*out = strdup(t);
return 5;
}
return 0;
}

现在我有:

int foo(char * s, char * t, char ** out) {
someFunction(s, t, out);
printf("%s", *out);
return 0;
}

int someFunction(char *s, char * t, char **out) {

int val = strcmp(s, t);
if (val == 0) {
*out = strdup(s);
return 1;
} else {
*out = strdup(t);
return 5;
}
return 0;
}

当我尝试执行 printf 时,出现段错误。 someFunction 应该期待 *out 吗?我想我还是很困惑。

最佳答案

如果我理解您的意图,则此代码是“正确的”。我假设你正在做一些事情

char *s = "foo";
char *t = "bar";
char *out;
foo(s, t, out);

当你真正想要的时候

char *s = "foo";
char *t = "bar";
char *out;
foo(s, t, &out); // Note the & which passes the address of a char* to be manipulated

关于c - 在 C 中处理多个函数中的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5628379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com