C ++ pointers and references need clarification

Which of the following please?

I understand that a pointer is an address of something of a specific type.

So, int i = 18 , a pointer to it int *pI = &i;

The following 2 listings are available

 void foo (int &something) // Will accept an address of something void bar (int *something) // Will accept a pointer to something 

When we declare a function as

 void bar (int *something) 

Better send a pointer to something. Indeed, foo(pI) works.

Following the same logic, looking at

 void foo (int &something) 

We need to send him the address of what points to int as an argument, and then:

Why is foo(&i) wrong?

+6
source share
5 answers

void foo (int &something) // Will accept an address of something

This is not true: int& is a reference, a concept similar to pointers in a certain way, but not identical.

References are like pointers that a value can be changed by reference, just as it can be changed by a pointer. However, there is no such thing as a null reference, while NULL pointers are very common.

When you call a function that accepts a link, you simply pass a variable to the link that you accept - no & operator is required:

 void foo (something); // "something" must be a variable 
+5
source

The void foo (int &something) declaration accepts a reference variable , not a pointer.

You name it exactly the same as you would call void foo (int something) , except that something passed by reference and not by value .

+2
source

void foo (int & something) // Will accept the address of something

No, although I can understand the confusion. This function refers to int . In a well-defined program, the links will be non-zero. It looks conceptually like a pointer, but semantically different.

You do not need to do anything to call this function.

 int i = 10; foo(i); // passed to foo by reference 
0
source

Because in C ++ it means "reference type" in the context of the function prototype, since you use it here. Your function:

 void foo (int &something) 

actually indicates that an integer reference type should be passed, so you simply call this function as follows:

 foo(i); 

Note that in this case, you still pass the address I to the function, but you do it as a reference type, not a raw pointer.

0
source

There are two different meanings for & .

The first is to create a pointer from an existing variable.

The second is to make a link.

Despite the fact that both of them use the same symbol, these are two completely different things.

0
source

Source: https://habr.com/ru/post/922254/


All Articles