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

发布于 2024-11-01 03:33:59 字数 687 浏览 0 评论 0原文

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

过去是:

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 吗?我想我还是很困惑。

I'm trying to create functions out of existing code in order to make it cleaner, and I'm having some problems:

It used to be:

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

Now I have:

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

And I'm getting segmentation faults when I try to do the printf. Should someFunction be expecting a *out? I guess I'm still confused.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

樱花落人离去 2024-11-08 03:33:59

如果我理解您的意图,则此代码是“正确的”。 的事情

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

This code is "correct" if I understand your intent. I assume you are doing something along the lines of

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

when you really want

char *s = "foo";
char *t = "bar";
char *out;
foo(s, t, &out);  // Note the & which passes the address of a char* to be manipulated
像你 2024-11-08 03:33:59

我会这样转换它:

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

I would convert it this way:

int foo(char * s, char * t, char ** out) {
    int val = strcmp(s, t); 
    *out = val ? strdup(t) : strdup(s);
    return val ? 5 : 1;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文