C错误 - 预期的声明说明符或' ...'之前' *'代币

时间:2016-11-22 08:16:20

标签: c pointers swap

我试图绕过指针,我试图编写一个程序,它将使用指针交换两个数字。但是,我收到了标题中所述的错误。这是我的代码:

    //This program swaps two numbers using pointers

#include <stdio.h>

void swap(*val1, *val2);

int main() {

    int num1, num2;
    int *pNum1, *pNum2;

    printf("Enter number 1:\n");
    scanf("%d", &num1);

    printf("Enter number 2:\n");
    scanf("%d", &num2);

    pNum1 = &num1;
    pNum2 = &num2;

    printf("Numbers not swapped: %d, %d\n", *pNum1, *pNum2);
    swap(pNum1, pNum2);


    return 0;
}

void swap(*val1, *val2) {

    int temp;

    temp = val1;
    val1 = val2;
    val2 = temp;

    printf("Numbers swapped: %d, %d\n", *val1, *val2);


    return;
}

1 个答案:

答案 0 :(得分:1)

void swap(*val1, *val2);

应该是

void swap(int *val1, int *val2);

然后你应该传递

swap(&num1,&num2);

如果您传递指针,那么您正在传递它的副本。您需要传递该地址。无需在调用函数中使用指针就可以直接传递变量的地址。

void swap(int *p,int *q)
{
   int t = *p;
   *p = *q;
   *q = t;

}