将指针数组传递给函数时,回调将如何发生?

时间:2019-06-12 12:20:36

标签: c pointers

当我通过排序函数传递一个指针数组时,我还有另一个交换函数。

我将哪些确切的变量(指针数组中的变量)传递给交换函数?

不使用交换功能,而是直接将其直接复制到排序中。

typedef struct team
{
  int val;
} team;

void swap(team *t1, team *t2);
void sort(team *t[4]);

void swap(team *t1, team *t2)
{
  team *t = t1;
  t1 = t2;
  t2 = t;
}

void sort(team *t[4])
{
  printf("t[0] is %d\n", t[0]);
  // I have a sorting algorithm here that uses this swap
  swap(t[0], t[1]);
  printf("t[0] is %d\n", t[0]);
}

int main()
{
  team table[4] = {2, 6, 7, 8};
  team *aop[4] = {&table[0], &table[1], &table[2], &table[3]};
  sort(aop);
  return 0;
}

顺便说一句,我在这里完全是个菜鸟,关于如何提出问题或编码的任何其他技巧将不胜感激。

2 个答案:

答案 0 :(得分:1)

您正在使用的交换函数按值获取其每个指针参数,但是,为实现所需的功能,需要通过(指针)引用获取它们。

这里要区别的是,交换(指针)引用采用team类型的值(即team *),但是按值采用team *类型的值。因此,它仅交换其本地引用,这就是如果将其直接插入您的sort函数中的原因。

请考虑以下swap

的实现
void swap(team **t1, team **t2)
{
  team *t = *t1;
  *t1 = *t2;
  *t2 = t;
}

在这种情况下,swap接受(指针)对类型team *的值的引用,并交换它们。现在,这将适用于预期的用例。

答案 1 :(得分:0)

您的swap函数什么都不做,因为C使用call by value。您必须将指针传递给指针:

void swap(team **t1, team **t2)
{
  team **t = t1;

  *t1 = *t2;
  *t2 = t;
}

现在,您将指针的地址传递到函数中,并在给定地址处处理数据。

t[0] is 2
t[0] is 6

您可以here对其进行测试。

编辑:上一个更快:)