Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a point in to a function

Tags:

c++

pointers

In this program I've created two pointers (a,b) that points to the memory address of x and y. In the function I've created its supposed to swap the memory address of a and b(So b=a and a=b). When I compile it gives me a error (invalid conversion from 'int' to 'int*') What does that mean? I'm passing a pointer to the function or is it read it as a regular 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;
}

error message:

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]

like image 527
Camilo Salazar Avatar asked Jun 29 '15 17:06

Camilo Salazar


People also ask

What is passing pointers to functions in C?

Pass-by-pointer means to pass a pointer argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the variable to which the pointer argument points.

Which is the correct way to pass a function pointer to arguments?

We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer. This process is known as call by reference as the function parameter is passed as a pointer that holds the address of arguments.

Are pointers passed by value?

Pointers are passed by value as anything else. That means the contents of the pointer variable (the address of the object pointed to) is copied. That means that if you change the value of the pointer in the function body, that change will not be reflected in the external pointer that will still point to the old object.


1 Answers

*a and *b are of type int, while a and b are both of type int*. Your function takes two int*'s, so all you have to do is change

pointer(*a,*b);

to

pointer(a,b);
like image 83
scohe001 Avatar answered Oct 03 '22 00:10

scohe001