[c++] C++ Passing Pointer to Function (Howto) + C++ Pointer Manipulation

I am a little confused as to how passing pointers works.

Let's say I have the following function and pointer, and...

EDIT:

...I want to use a pointer to some object as an argument in the function.

i.e.:

void Fun(int Pointer){
    int Fun_Ptr = ---Passed Pointer---; 
    //So that Fun_Ptr points to whatever ---Passed Pointer points to

Between the *Pointer and &Pointer notations, I am very confused. I know that *Pointer means give whatever it points to.

Do I put void (int *pointer) in the declaration. What about when I use the function?

Your assistance is appreciated.

EDIT 2:

Okay, I now understand that using *variable in a declaration means that a pointer will be passed. However, what about when i use the function?

i.e.

int main(){
    int foo;
    int *bar;
    bar = foo;
    Fun(bar);
}

EDIT 3: Okay, so correct me if I am wrong:

According to the conventions of the above code:

bar = &foo means: Make bar point to foo in memory

*bar = foo means Change the value that bar points to to equal whatever foo equals

If I have a second pointer (int *oof), then:

bar = oof means: bar points to the oof pointer

bar = *oof means: bar points to the value that oof points to, but not to the oof pointer itself

*bar = *oof means: change the value that bar points to to the value that oof points to

&bar = &oof means: change the memory address that bar points to be the same as the memory address that oof points to

Do I have this right?

EDIT 4: Thanks so much for all your help (I wish I could accept more than 1 answer, but I have to go with the first one. I am not sure how a community wiki works exactly, but I will leave it this way for editing (feel free to turn it into a ref guide if you like).

This question is related to c++ pointers function arguments

The answer is


void Fun(int *Pointer)
{
  //if you want to manipulate the content of the pointer:
  *Pointer=10;
  //Here we are changing the contents of Pointer to 10
}

* before the pointer means the content of the pointer (except in declarations!)

& before the pointer (or any variable) means the address

EDIT:

int someint=15;
//to call the function
Fun(&someint);
//or we can also do
int *ptr;
ptr=&someint;
Fun(ptr);

To declare a function that takes a pointer to an int:

void Foo(int *x);

To use this function:


int x = 4;
int *x_ptr = &x;
Foo(x_ptr);
Foo(&x);

If you want a pointer for another type of object, it's much the same:

void Foo(Object *o);

But, you may prefer to use references. They are somewhat less confusing than pointers:


// pass a reference
void Foo(int &x)
{
  x = 2;
}

//pass a pointer
void Foo_p(int *p)
{
   *x = 9;
}

// pass by value
void Bar(int x)
{
   x = 7;
}
int x = 4;
Foo(x);  // x now equals 2.
Foo_p(&x); // x now equals 9.
Bar(x);  // x still equals 9.

With references, you still get to change the x that was passed to the function (as you would with a pointer), but you don't have to worry about dereferencing or address of operations.

As recommended by others, check out the C++FAQLite. It's an excellent resource for this.

Edit 3 response:

bar = &foo means: Make bar point to foo in memory

Yes.

*bar = foo means Change the value that bar points to to equal whatever foo equals

Yes.

If I have a second pointer (int *oof), then:

bar = oof means: bar points to the oof pointer

bar will point to whatever oof points to. They will both point to the same thing.

bar = *oof means: bar points to the value that oof points to, but not to the oof pointer itself

No. You can't do this (assuming bar is of type int *) You can make pointer pointers. (int **), but let's not get into that... You cannot assign a pointer to an int (well, you can, but that's a detail that isn't in line with the discussion).

*bar = *oof means: change the value that bar points to to the value that oof points to

Yes.

&bar = &oof means: change the memory address that bar points to be the same as the memory address that oof points to

No. You can't do this because the address of operator returns an rvalue. Basically, that means you can't assign something to it.


It might be easier for you to understand using Functionoids which are expressively neater and more powerful to use, see this excellent and highly recommended C++ FAQ lite, in particular, look at section 33.12 onwards, but nonetheless, read it from the start of that section to gain a grasp and understanding of it.

To answer your question:

typedef void (*foobar)() fubarfn;

void Fun(fubarfn& baz){
   fubarfn = baz;
   baz();
}

Edit:

  • & means the reference address
  • * means the value of what's contained at the reference address, called de-referencing

So using the reference, example below, shows that we are passing in a parameter, and directly modify it.

void FunByRef(int& iPtr){
    iPtr = 2;
}

int main(void){
    // ...
    int n;
    FunByRef(n);
    cout << n << endl; // n will have value of 2
}

void Fun(int* Pointer)   -- would be called as Fun( &somevariable )

would allow you to manipulate the content of what 'Pointer' points to by dereferencing it inside the Fun function i.e.

*Pointer = 1;

declaring it as above also allows you also to manipulate data beyond what it points to:

int foo[10] = {0};
Fun(foo);

in the function you can then do like *(Pointer + 1) = 12; setting the array's 2nd value.

void Fun(int& Pointer)  -- would be called Fun( somevariable )

you can modify what Pointer references to, however in this case you cannot access anything beyond what Pointer references to.


If you want to pass a pointer-to-int into your function,

Declaration of function (if you need it):

void Fun(int *ptr);

Definition of function:

void Fun(int *ptr) {
    int *other_pointer = ptr;  // other_pointer points to the same thing as ptr
    *other_ptr = 3;            // manipulate the thing they both point to
}

Use of function:

int main() {
    int x = 2;
    printf("%d\n", x);
    Fun(&x);
    printf("%d\n", x);
}

Note as a general rule, that variables called Ptr or Pointer should never have type int, which is what you have then in your code. A pointer-to-int has type int *.

If I have a second pointer (int *oof), then:

bar = oof means: bar points to the oof pointer

It means "make bar point to the same thing oof points to".

bar = *oof means: bar points to the value that oof points to, but not to the oof pointer itself

That doesn't mean anything, it's invalid. bar is a pointer *oof is an int. You can't assign one to the other.

*bar = *oof means: change the value that bar points to to the value that oof points to

Yes.

&bar = &oof means: change the memory address that bar points to be the same as the memory address that oof points to

Nope, that's invalid again. &bar is a pointer to the bar variable, but it is what's called an "rvalue", or "temporary", and it cannot be assigned to. It's like the result of an arithmetic calculation. You can't write x + 1 = 5.

It might help you to think of pointers as addresses. bar = oof means "make bar, which is an address, equal to oof, which is also an address". bar = &foo means "make bar, which is an address, equal to the address of foo". If bar = *oof meant anything, it would mean "make bar, which is an address, equal to *oof, which is an int". You can't.

Then, & is the address-of operator. It means "the address of the operand", so &foo is the address of foo (i.e, a pointer to foo). * is the dereference operator. It means "the thing at the address given by the operand". So having done bar = &foo, *bar is foo.


To pass a pointer to an int it should be void Fun(int* pointer).

Passing a reference to an int would look like this...

void Fun(int& ref) {
   ref = 10;
}

int main() {
   int test = 5;
   cout << test << endl;  // prints 5

   Fun(test);
   cout << test << endl;  // prints 10 because Fun modified the value

   return 1;
}

Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to pointers

Method Call Chaining; returning a pointer vs a reference? lvalue required as left operand of assignment error when using C++ Error: stray '\240' in program Reference to non-static member function must be called How to convert const char* to char* in C? Why should I use a pointer rather than the object itself? Function stoi not declared C pointers and arrays: [Warning] assignment makes pointer from integer without a cast Constant pointer vs Pointer to constant How to get the real and total length of char * (char array)?

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to arguments

docker build with --build-arg with multiple arguments ARG or ENV, which one to use in this case? How to have multiple conditions for one if statement in python Gradle task - pass arguments to Java application Angularjs - Pass argument to directive TypeError: method() takes 1 positional argument but 2 were given Best way to check function arguments? "Actual or formal argument lists differs in length" Python: Passing variables between functions Print multiple arguments in Python