c++ - Passing a point in to a function -
in program i've created 2 pointers (a,b) points memory address of x , y. in function i've created supposed swap memory address of , b(so b=a , a=b). when compile gives me error (invalid conversion 'int' 'int*') mean? i'm passing pointer function or read regular int?
#include <iostream> using std::cin; using std::cout; using std::endl; void pointer(int* x,int* y)// swaps memory address a,b { int *c; *c = *x; *x = *y; *y = *c; } int main() { int x,y; int* = &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 swap of memory address return 0; }
error message:
c++.cpp: in function 'int main()':
c++.cpp:20:16: error: invalid conversion 'int' 'int*' [-fpermissive]
c++.cpp:6:6: error: initializing argument 1 of 'void pointer(int*, int*)' [-fpermissive]
c++.cpp:20:16: error: invalid conversion 'int' 'int*' [-fpermissive]
c++.cpp:6:6: error: initializing argument 2 of 'void pointer(int*, int*)' [-fpermissive]
in function call
pointer(*a,*b);
expressions *a
, *b
have type int
while corresponding parameters of function have type int *
.
if want swap 2 pointers , not values (objects x , y) pointed pointers function should following way
void pointer( int **x, int **y )// swaps memory address a,b { int *c = *x; *x = *y; *y = c; }
and called like
pointer( &a, &b );
or define parameters having reference types. example
void pointer( int * &x, int * &y )// swaps memory address a,b { int *c = x; x = y; y = c; }
and call like
pointer( a, b );
Comments
Post a Comment