在这个程序中,我创建了两个指针(a,b),指向x和y的内存地址.在我创建的函数中,它应该交换a和b的内存地址(So 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;
}
Run Code Online (Sandbox Code Playgroud)
错误信息:
C++.cpp:在函数'int main()'中:
C++.cpp:20:16:错误:从'int'无效转换为'int*'[-fpermissive]
C++.cpp:6:6:错误:初始化参数1'void pointer(int*,int*)'[ - fremissive]
C++.cpp:20:16:错误:从'int'无效转换为'int*'[-fpermissive]
C++.cpp:6:6:错误:初始化'void pointer(int*,int*)'[-fpermissive]的参数2
在这个函数中调用
pointer(*a,*b);
Run Code Online (Sandbox Code Playgroud)
表达式*a
和*b
具有类型int
,而函数的相应参数具有类型int *
。
如果您想交换两个指针而不是指针指向的值(对象 x 和 y),则该函数应如下所示
void pointer( int **x, int **y )// Swaps the memory address to a,b
{
int *c = *x;
*x = *y;
*y = c;
}
Run Code Online (Sandbox Code Playgroud)
并称其为
pointer( &a, &b );
Run Code Online (Sandbox Code Playgroud)
或者您可以将参数定义为具有引用类型。例如
void pointer( int * &x, int * &y )// Swaps the memory address to a,b
{
int *c = x;
x = y;
y = c;
}
Run Code Online (Sandbox Code Playgroud)
并称其为
pointer( a, b );
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
131 次 |
最近记录: |