I am trying to run the following code, but I am getting the following error.
error: cannot declare pointer to 'int&'
#include <iostream>
using namespace std;
int main()
{
int x = 5;
int *ptr = &x;
int &(*y) = ptr;
*y = 5;
cout << *ptr << endl;
return 0;
}
You declare references to pointers the same way you declare references to basic types.
Consider:
int main()
{
int i = 0; // int
int& ir = i; // int reference (reference to int)
int* ip = &i; // int pointer (pointer to int)
int*& ipr = ip; // int pointer reference (reference to pointer to int)
*ip = 5;
cout << *ipr << endl;
return 0;
}
If you just want a new pointer to the same region of memory, use:
int *y = ptr;
This not so much an "alias" in that if you change *ptr or *y, both will change, but if you change the pointers themselves, the other will not be updated.
If you actually do want a reference to a pointer, use:
int *&y = ptr;
int *ptr = &x;
pointer value has an address and a type of x.
when you typed code above, the value of ptr is an address of x, and ptr know the type of x.
int * (&y) = ptr;
the code above is declaring variable 'y' (type:int*, define:ptr's reference)
reference variables should be declared and defined simultaneously.
anyway, as a result, ptr and y are pointing same memory address.
you can easily think y is a nickname of ptr.
so you can access the variable 'x' by using y, instead of ptr.
v - a variable name.
&v - a variable that will be a reference of something.
*&v - a variable that will be a reference of a pointer to something
int *&v - a variable that will be a reference of a pointer to int
Or for a more interesting example,
(*&v)[5] - a variable that will be a reference of a pointer to an array of 5 something
int (*&v)[5] - a variable that will be a reference of a pointer to an array of 5 int
Related
I am totally newbie and have hard time digesting pointer section in C++.
What I have understood is this:
to access the content of the address, use *
to access the address of the content, use &
So basically my question is this: why is the codes below throw errors?
int x = 10;
int *pt;
*pt = x;
Why should I code in formats like the below?
int x = 10;
int *pt;
pt = &x;
Also I can't understand *pt = &x; line. *pt should be the content, not the address. Why is it ok?
int x = 10;
int *pt = &x;
Similarly, to make temp share the same address with n1, I think it should be
int n1 = 1;
int &temp = &n1;
but textbook says right code is below.
int n1 = 1;
int &temp = n1;
Need HELP!
You are confusing the meaning of * and & in the expression with their meaning in variable type declaration. In variable type * just means that this variable is a pointer, while & means that it is a reference, e.g.:
int *pt = &x;
actually means "declare a pointer to int with name pt and assign the address of x to it". While
int &temp = n1;
means "declare a reference to int named temp and assign n1 to it, so that temp refers to the same memory as n1".
I think you are confusing about mean of '&' and '*'.
In a nutshell,
&x: A bowl of x address.
*pt: A fork for choose address(only address).
And if you declare as 'int *pt', you don't need to declare as '*pt=&x'. Because 'pt' is already pointer variable.
Pointer is a "reference to memory for particular type". In example you wrote int *pt; Instead try to think about it like:
int x = 10;
// Declare a pointer to location in memory.
// That memory is holding (or will be) value of type int.
int* pt;
// What would be be the meaning of this? *pt doesn't really mean anything.
// int* means that it is points to type of integer
*pt = x;
Similar approach is for the &x, which is only shortcut for:
"I know that there is variable x of type int and I would like to get address (of first byte of that int)".
// Again from the example, you declare int x to value 10.
int x = 10;
// Declare pointer for int type.
int* pt;
// Set pointer (variable that specifies the location in memory)
// to address of variable x (so you point "pointer pt" to location in memory
// where variable x sits
pt = &x;
Finally if you connect the dots:
int x = 10;
// 1st declare pointer of type int
// point the pointer to the value x
int* pt = &x;
why is the codes below throw errors?
1> int x = 10;
2> int *pt;
3> *pt = x;
*pt in line 3 accesses the int pointed to by pt, but at this time the value of pt is undefined.
Why should I code in formats like the below?
int x = 10;
int *pt;
pt = &x;
Assign a pointer that points to x to pt, so now the pointer pt points to x.
Also i can't understand *pt = &x; line. *pt should be the content, not
the address. Why is it ok?
int x = 10;
int *pt = &x;
No, pt is a variable and int * is its type. This code has the same meaning as the previous one.
Similarly, to make temp share the same address with n1, i think it
should be
int n1 = 1;
int &temp = &n1;
but textbook says right code is below.
int n1 = 1;
int &temp = n1;
int & is a C++ reference type, it is not a pointer, so the & operator is not needed to get the address of n1. At this time pt is already binded to n1.
I have a function similar to this:
#include <iostream>
#include <string>
void increaseRef(int& x) {
x += 3;
std::cout << x << std::endl;
}
Now I have a pointer that should be passed to this function, I can deference it:
int main(int argc, char const* argv[])
{
int* x;
*x = 3;
increaseRef(*x);
return 0;
}
Or not:
int main(int argc, char const* argv[])
{
int* x;
*x = 3;
increaseRef(x);
return 0;
}
In the second case I got an error:
main.cpp:15:15: error: invalid initialization of reference of type ‘int&’ from expression of type ‘int*’
increaseRef(x);
In the first case I got a segfault.
First of all, you can't do this:
int* x;
*x = 3;
because x doesn't point to a valid int. De-referencing it us undefined behaviour.
You could do this:
int y = 3;
int* x = &y;
Then you can pass *x to the function.
increaseRef(*x);
After the edit, I see your point better.
In the second case, you are referencing the reference itself.
In other terms, you are giving an &(int*) to the function instead of an &(int).
Otherwise:
You are not allocating any memory for your pointer.
You need to call malloc() or new() before you can dereference the pointer.
Try
int *x=new int;
*x=3;
increaseRef(*x);
delete x; //and don't forget to delete your pointers, or you will leak memory.
return 0;
You can also pass the allocation to c++ by defining a local variable, as #juanchopanza stated. That way, memory will be automatically freed on return (and the variable will be created on the stack), the downside being that after your function defining the given variable returns, your pointer will be invalid, and if you dereference it outside the function, you will get a segfault.
I am trying to reference an array by using pointers
double a[5];
double*& b = a; //doesn't compile
double*& b = &a[0]; //doesn't compile either
double*& b = &static_cast<double*>(a); //nope
Is there any way to make it so that b is binded to the address of the first element of the array?
thanks!
To reference an array by using pointers, you don't need anything
special:
double* b = a;
If you want a pointer to the entire array, rather than to just
the first element, it is:
double (*b)[5] = &a;
, but this very unusual, and will enormously confuse any reader.
If you want a reference to the entire array (no pointer):
double (&b)[5] = a;
This is often used as a function parameter, but I've never seen
it used elsewhere.
If you want a reference to a pointer designating the first
element, it has to be const, because the result of a conversion
(including the array to pointer conversion) is an rvalue, and
cannot be bound to a non-const reference:
double *const (&b) = a;
And if you really need a non-const reference to a pointer,
you'll have to introduce a pointer variable:
double* pa = a;
double* (&b) = pa;
As others have remarked, you don't need a reference-to-a-pointer, just use a pointer-to-double.
double *b = a;
The reason why you can't assign a to a reference-to-a-pointer is because the silent conversion from array-of-double to pointer-to-double results in an rvalue.
If you have to use a reference to pointer, you should make it a reference to const pointer, const references can bind to rvalues:
double a[5];
double * const &b = a;
You can get a pointer to the first element:
double * b = a;
or a const reference to an unnamed pointer to it:
double * const & b = a;
or a reference to the array:
double (&b)[5] = a;
but there's no way get a non-const reference to a pointer without a pointer variable to refer to.
In this program a pointer an array is used:
//#include <conio.h>
#include <iostream>
using namespace std;
int main()
{
int a[5] = {1,2,3,4,5};
int b[5] = {6,7,8,9,10};
int (*pa[4])[5] = {&a,&b,&a,&b};
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 5; j++)
cout<< (*pa[i])[j] << "
cout<< "\n";
}
//_getch();
cin.get();
}
In some compilers comparison of &a and a is allowed. For example this code can be compiled in (old) Borland compilers:
//#include <conio.h>
#include <iostream>
using namespace std;
int main()
{
int a[20];
cout<< (a == &a);
//_getch();
cin.get();
}
and the output is 1. But in previous program instead of
int (*pa[4])[5] = {&a,&b,&a,&b};
one cannot write
int (*pa[4])[5] = {a,b,a,b};
Is it possible to make a pointer variable hold the address of another pointer variable? eg:int a;
int *ptr,*ptr1;
ptr=&a;
ptr1=&ptr;
Sure, a pointer to a pointer.
int i;
int *pi = &i;
int **ppi = π
There is nothing particularly unusual about a pointer to a pointer. It's a variable like any other, and it contains the address of a variable like any other. It's just a matter of setting the correct type so that the compiler knows what to do with them.
Yes, but it needs to have the right type. In your example int *ptr,*ptr1; both ptr and ptr1 have type "pointer to int", which can only point to an int, not a pointer. If you declare int *ptr, **ptr1;, then ptr1 has type "pointer to int *" and thus can point to ptr.
Here's a sample showing what happens
int a = 13;
int *ptr,
int **ptr1; // ** means pointer to pointer
ptr = &a;
ptr1 = &ptr;
cout << a; //value of a
cout << *ptr; //ptr points to a, *ptr is value of a
cout << **ptr1; //same as above
cout << &ptr; //prints out the address of ptr
cout << *ptr1; //same as above
It works the same for int ***ptr, int ****ptr.
Pointer to pointer is possible (and very common), but int* may not be large enough to contain the address of another int*. use int**. (or void*, for generally pointer)
There's two answers here and they're both yes.
Two pointers can point to the same location
int b, *p1=&b, *p2=&b;
*p1 = 123;
*p2; // equals 123
You can also have a pointer to a pointer:
int x=2, y=3, *p=&x, **q=&p;
Note the extra asterisk.
**q; // equals 2
*q = &y;
**q; // equals 3
**q = 4;
y; // equals 4
Yes,
Pls see the following code. I hope it will serve your purpose
int a = 4;
int *ptr = &a;
int *ptr1 = (int*)&ptr;
cout << **(int**)ptr1;
Here ptr1 is single pointer but behaves as double pointer
I found these symbols in a function declaration several times, but I don't know what they mean.
Example:
void raccogli_dati(double **& V, double **p, int N) {
int ultimo = 3;
V = new double * [N/2];
for(int i=0; i < N/2; i++) {
V[i] = new double[N/2], std :: clog << "digita " << N/2 - i
<< " valori per la parte superiore della matrice V: ";
for(int j=i; j < N/2; j++)
std :: cin >> V[i][j], p[ultimo++][0] = (V[i][j] /= sqrt(p[i][0]*p[j][0]));
}
for(int i=1; i < N/2; i++)
for(int j=0; j < i; j++)
V[i][j] = V[j][i];
}
That is taking the parameter by reference. So in the first case you are taking a pointer parameter by reference so whatever modification you do to the value of the pointer is reflected outside the function. Second is the simlilar to first one with the only difference being that it is a double pointer. See this example:
void pass_by_value(int* p)
{
//Allocate memory for int and store the address in p
p = new int;
}
void pass_by_reference(int*& p)
{
p = new int;
}
int main()
{
int* p1 = NULL;
int* p2 = NULL;
pass_by_value(p1); //p1 will still be NULL after this call
pass_by_reference(p2); //p2 's value is changed to point to the newly allocate memory
return 0;
}
First is a reference to a pointer, second is a reference to a pointer to a pointer. See also FAQ on how pointers and references differ.
void foo(int*& x, int**& y) {
// modifying x or y here will modify a or b in main
}
int main() {
int val = 42;
int *a = &val;
int **b = &a;
foo(a, b);
return 0;
}
That's passing a pointer by reference rather than by value. This for example allows altering the pointer (not the pointed-to object) in the function is such way that the calling code sees the change.
Compare:
void nochange( int* pointer ) //passed by value
{
pointer++; // change will be discarded once function returns
}
void change( int*& pointer ) //passed by reference
{
pointer++; // change will persist when function returns
}
An int* is a pointer to an int, so int*& must be a reference to a pointer to an int. Similarly, int** is a pointer to a pointer to an int, so int**& must be a reference to a pointer to a pointer to an int.
*& signifies the receiving the pointer by reference. It means it is an alias for the passing parameter. So, it affects the passing parameter.
#include <iostream>
using namespace std;
void foo(int *ptr)
{
ptr = new int(50); // Modifying the pointer to point to a different location
cout << "In foo:\t" << *ptr << "\n";
delete ptr ;
}
void bar(int *& ptr)
{
ptr = new int(80); // Modifying the pointer to point to a different location
cout << "In bar:\t" << *ptr << "\n";
// Deleting the pointer will result the actual passed parameter dangling
}
int main()
{
int temp = 100 ;
int *p = &temp ;
cout << "Before foo:\t" << *p << "\n";
foo(p) ;
cout << "After foo:\t" << *p << "\n";
cout << "Before bar:\t" << *p << "\n";
bar(p) ;
cout << "After bar:\t" << *p << "\n";
delete p;
return 0;
}
Output:
Before foo: 100
In foo: 50
After foo: 100
Before bar: 100
In bar: 80
After bar: 80
Typically, you can read the declaration of the variable from right to left. Therefore in the case of int *ptr; , it means that you have a Pointer * to an Integer variable int. Also when it's declared int **ptr2;, it is a Pointer variable * to a Pointer variable * pointing to an Integer variable int , which is the same as "(int *)* ptr2;"
Now, following the syntax by declaring int*& rPtr;, we say it's a Reference & to a Pointer * that points to a variable of type int. Finally, you can apply again this approach also for int**& rPtr2; concluding that it signifies a Reference & to a Pointer * to a Pointer * to an Integer int.
To understand those phrases let's look at the couple of things:
typedef double Foo;
void fooFunc(Foo &_bar){ ... }
So that's passing a double by reference.
typedef double* Foo;
void fooFunc(Foo &_bar){ ... }
now it's passing a pointer to a double by reference.
typedef double** Foo;
void fooFunc(Foo &_bar){ ... }
Finally, it's passing a pointer to a pointer to a double by reference. If you think in terms of typedefs like this you'll understand the proper ordering of the & and * plus what it means.
This *& in theory as well as in practical its possible and called as reference to pointer variable. and it's act like same.
This *& combination is used in as function parameter for 'pass by' type defining. unlike ** can also be used for declaring a double pointer variable.
The passing of parameter is divided into pass by value, pass by reference, pass by pointer.
there are various answer about "pass by" types available. however the basic we require to understand for this topic is.
pass by reference --> generally operates on already created variable refereed while passing to function e.g fun(int &a);
pass by pointer --> Operates on already initialized 'pointer variable/variable address' passing to function e.g fun(int* a);
auto addControl = [](SomeLabel** label, SomeControl** control) {
*label = new SomeLabel;
*control = new SomeControl;
// few more operation further.
};
addControl(&m_label1,&m_control1);
addControl(&m_label2,&m_control2);
addControl(&m_label3,&m_control3);
in the above example(this is the real life problem i came across) i am trying to init few pointer variable from the lambda function and for that we need to pass it by double pointer, so that comes with d-referencing of pointer for its all usage inside of that lambda + while passing pointer in function which takes double pointer, you need to pass reference to the pointer variable.
so with this same thing reference to the pointer variable, *& this combination helps. in below given way for the same example i have mentioned above.
auto addControl = [](SomeLabel*& label, SomeControl*& control) {
label = new SomeLabel;
control = new SomeControl;
// few more operation further.
};
addControl(m_label1,m_control1);
addControl(m_label2,m_control2);
addControl(m_label3,m_control3);
so here you can see that you neither require d-referencing nor we require to pass reference to pointer variable while passing in function, as current pass by type is already reference to pointer.
Hope this helps :-)