gpt4 book ai didi

c++ - 将一个点传递给一个函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:14:28 24 4
gpt4 key购买 nike

在这个程序中,我创建了两个指向 x 和 y 的内存地址的指针 (a,b)。在我创建的函数中,它应该交换 a 和 b 的内存地址(所以 b=a 和 a=b)。当我编译时它给我一个错误(从'int'到'int*'的无效转换)这是什么意思?我正在传递一个指向该函数的指针,还是将其作为常规 int 读取?

#include <iostream>
using std::cin;
using std::cout;
using std::endl;
void pointer(int* x,int* y)// Swaps the memory address to a,b
{
int *c;
*c = *x;
*x = *y;
*y = *c;
}

int main()
{
int x,y;
int* a = &x;
int* b = &y;
cout<< "Adress of a: "<<a<<" Adress of b: "<<b<<endl; // Display both memory address

pointer(*a,*b);
cout<< "Adress of a: "<<a<<" Adress of b: "<<b<<endl; // Displays the swap of memory address

return 0;
}

错误信息:

C++.cpp: In function 'int main()':
C++.cpp:20:16: error: invalid conversion from 'int' to 'int*' [-fpermissive]
C++.cpp:6:6: error: initializing argument 1 of 'void pointer(int*, int*)' [-fpermissive]
C++.cpp:20:16: error: invalid conversion from 'int' to 'int*' [-fpermissive]
C++.cpp:6:6: error: initializing argument 2 of 'void pointer(int*, int*)' [-fpermissive]

最佳答案

*a*bint类型,而ab 都是 int* 类型。你的函数需要两个 int*,所以你所要做的就是改变

pointer(*a,*b);

pointer(a,b);

关于c++ - 将一个点传递给一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31122043/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com