3

首先,我知道这应该已经在 SO 的某个地方得到了回答,但我似乎找不到正确的帖子。因此,如果它是重复的,请指向我回答这个问题的帖子,我将删除它。

我有一个复制字符串的函数:

static int read_ad_content(json_t * root, char* content)
{

  [.. stuff happens]

  const char* tmp = json_string_value(json_content);
  unsigned int size = strlen(tmp);
  content = (char*)malloc(size + 1);
  memcpy(content, tmp, size);
  content[size] = '\0'; // <= I checked and content is NOT null here!

  return 0;
}

我在我的主要功能中这样称呼它:

char *ad_content;
if (read_ad_content(ad_json, ad_content) != 0)
  {
     log_err(argv, "Failed to extract information");
  }

  if (ad_content == NULL)
  {
    // <= I always end up here
  }

我知道这应该很容易,但我只是不知道如何解决这个问题。

4

1 回答 1

3

在 C 中,参数是按值传递的。您正在做的与以下内容没有什么不同:

void brokenMethod(int a){
    a = 10;
}

int a = 0;
brokenMethod(a);
if(a == 0)
{
    //always end up here!
}

当然,你总是会在那里结束。a 从未修改过!a 的值被传递给了 brokenMethod,它可以做任何它想做的事情,但这不会影响你外部范围内的 a 的值。

如果我希望该方法填充一个 int,我必须将它传递给一个指向 int 的指针。

void fixedMethod(int* a)
{
    *a = 10; 
    //Remember, you want to modify the thing being pointed at, not the thing doing the pointing!
    //a = something; is going to have the exact same problem as the first example
}

int a = 0;
fixedMethod(&a);
if(a == 0)
{
    //Better
}

上面的示例将值粘贴到 int 中。在您的情况下,如果您希望该方法填充指向 int 的指针,那么您必须将指针传递给指向 int 的指针。

侧边栏: 您可能还会发现通过参数返回值的方法难以推理并且更可能包含错误。如果您试图返回一个指向 int 的指针,只需有一个返回指向 int 的指针的方法。

int* HonestMethod()
{
    return pointer to whatever.
}
于 2013-10-07T22:27:58.887 回答