C:交换两个指针值

时间:2018-11-21 17:41:45

标签: c pointers swap

我想使用指针交换2个整数的值。

void swap(int *a, int *b)
{
    int *temp;
    temp = &a;

    *a = *b;
    *b = *temp;
}

为什么这不起作用?

给出错误:

incompatible pointer types initializing 'int *' with an expression of type 'int **'

1 个答案:

答案 0 :(得分:3)

temp是一个指针。您想要的是inta所指向的值。您需要将temp更改为int

void swap(int *a, int *b)
{
    int temp;
    temp = *a;

    *a = *b;
    *b = *temp;
}

您可能需要按照C的一些教程来理解指针的工作方式。对于Stack Overflow答案以及在线和书籍中提供的大量可用资源,要进行大量解释。