haosmark
haosmark

Reputation: 1127

How can I correctly pass a pointer to a function?

I can't seem to pass pointer to memory address. I thought the following code would pass the memory address that ptr points at, to my func(), then when I print out the address within func() it would show the same address as ptr did from within main(), however that's not what I'm seeing. p's address is different from ptr's address.

How do I correctly pass a pointer to functions?

#include <iostream>
using namespace std;

void func(int* p)
{
    printf("p address: %p\r\n", &p);
}

int main()
{
    int* ptr;
    memset(&ptr, 0, sizeof(int));
    printf("ptr address: %p\r\n", &ptr);
    func(ptr);
}

Upvotes: 0

Views: 320

Answers (2)

john
john

Reputation: 87959

Here's the code I think you are looking for

void func(int* p)
{
    printf("%p\n", p);
}

int main()
{
    int something = 0;
    int* ptr = &something;
    printf("%p\n", ptr);
    func(ptr);
}

Note there is only one & in the whole program when I initialise the pointer in main. It's using & when it isn't needed that was your main problem I believe.

Upvotes: 2

cigien
cigien

Reputation: 60228

In this declaration:

void func(int* p)

the variable p is indeed a copy of ptr, and so they have different memory addresses. The same rules apply here as they do for an int parameter. There's nothing special about pointers in this context. Don't be confused by the fact that the pointed at values are the same, i.e *p and *ptr are the same. The objects p and ptr are still copies of each other, and have different addresses.

If you want the argument p to have the same address as ptr, accept it by reference:

void func(int* &p)

Of course, they both still point at the same address as well.

Upvotes: 2

Related Questions