Pointers to Pointers (C++) - c++

Ok I understand the concept of pointers to pointers. But I don't know why this doesn't work.
void function(int **x)
{
*x = 10;
}
I keep getting the error:
a value of type "int" cannot be assigned to an entity of type "int*"
What am I doing wrong or what am I not understanding about pointers to pointers?
omg x_x I was confusing C with C++.

x is a pointer to a pointer so you have to dereference it twice to get to the actual object. E.g. **x = 10;

Ok I understand the concept of pointers to pointers.
Nah...
*x is an int*, so you can't assign an int to it.
The concept of pointers-to-pointers comes from C, where references aren't available. It allows reference semantics - i.e. you can change the original pointer.

In short, you need to dereference twice.
A dereference returns the thing a pointer is ponting to, so:
int n = 10; //here's an int called n
int* pInt = &n; //pInt points to n (an int)
int** ppInt = &pInt //ppInt points to pInt (a pointer)
cout << ppInt; //the memory address of the pointer pInt (since ppInt is pointing to it)
cout << *ppInt; //the content of what ppInt is pointing to (another memory address, since ppInt is pointing to another pointer
cout << *pInt; //the content of what pInt is pointing to (10)
cout << **ppInt; //the content of what the content of ppInt is pointing to (10)

x is pointing to a type of int *, not int. You either want to do static int i = 10; *x = &i or **x = 10.

Related

Why Do I get the memory adress instead of the real value ? Pointer c++

int x = 2;
int y=8;
int* p = &x;
*p=y;
cout << p <<endl;
my question is: why do I get the memory adress when I Print p and not the actual value since I already dereferenced it in line 4
cout << *p << endl;
is what you need.
When you try to output something to stdout, compiler automatically infer its type and call the corresponding function. In your case, p is pointer type, therefore the address is printed, and since *p is int type, you should use *p if you want to print the value.
I think you have a misconception about dereferencing pointers.
...since I already dereferenced it in line 4
Dereferencing means to retrieve the value the pointer is pointing to. It doesn't change the pointer itself in any way. p is still a pointer after *p=y;.
All *p=y does, is to change the value p is pointing to, it doesn't change the pointer itself.

c++ Pointer of pointer gives a value?

I am wondering one thing, I am trying to remember c++ after long working with c# :)
And one thing bugs me, and I don't know why it is happening.
Pointer should be thing, which points somewhere to memory(it's address)
And pointer of pointer is address of the pointer. Simple, right? :D
Let's take a look at this code:
#include <iostream>
int main()
{
int* TestMas = new int[10]
{
1,2,3,4,5,6,7,8,9
};
for (size_t i = 0; i < 10; i++)
{
printf("%d\t", *(TestMas+i));
}
}
For some reason, values are printed out instead of the addresses, it should be *(TestMas+i) should be address of the array pointer, but how values are printed out, and not address?
If I try to use & to dereference the pointer, I get an error xD How is it working?
TestMas is a int *, or the address of an integer. When you assign it to new int[10], you're pointing it to the first of 10 contiguous integers in memory that you guarantee belong to you.
So when you do *(TestMas + i), you're doing pointer arithmetic, and then dereferencing the new pointer. Note that the syntactic sugar for exactly this operation would be TestMas[i].
You probably meant to leave off the dereference if you just wanted the address. So just:
std::cout << TestMas + i;
TestMas is a pointer to an int, not a pointer to a pointer. Its type is int *. A pointer to a pointer to an int would be int **
TestMas + i is also a pointer to an int, pointing to the i-th element of the array. *(TestMas + i) is calling the indirection operator on that pointer, which returns the object or function pointed-to by the pointer operand, not the address.
The address is the value of (TestMas+i) itself.
You can print it with:
printf("%p\t", (TestMas+i) );

Why can't I directly assign an int to an int pointer like this: int *p = 6;?

error: invalid conversion from 'int' to 'int*'
int *q = 8;
Works fine.
*q = 6;
Why can't I directly assign an int to an int pointer like this: int *q = 6; and I can assign it safely in the next line?
Because they're different things at all. The 1st one is definition of variable with initializer expression, i.e an initialization (of the pointer itself):
int * q = 8;
~~~~~ ~ ~~~
type is int*; name of variable is q; initialized with 8
The 2nd one is assignment (of the object pointed by the pointer):
*q = 6;
~~ ~~~
dereference on q via operator*; assign the resulting lvalue pointed by q to 6
And, int *p = 6; means define a variable named p with type int* and initialize it with 6, which fails because 6 can't be used for initializing a pointer directly (i.e. the error "invalid conversion from 'int' to 'int*'").
* symbol is reused for two different purpuses in your snippet. First time it is used as a part of type declaration int *, declaring a pointer to int. Second time it is used to dereference a pointer *q, invoking indirection operator.
* can also be used to invoke multiplication operator *q = *q * *q;;
To assign a value to an integer pointed by pointer you need to dereference it. And to assigning integral value other than 0 to a pointer itself (that is what int *q = 8; is doing) requires reinterpret_cast, hence you get this error.
Statement int *q defines a variable of type "pointer to integer", and an initialisation therefore needs to be a pointer value, not an integral value.
So int *q = 8 is not the same as int *q; *q = 8 (which would be undefined behaviour because it dereferences an uninitialized pointer), but more like int *q; q = 8, which makes the misunderstanding more transparent.
This:
int *q = 8;
is an initialization. It initializes q (the pointer), not *q (what it points to). Writing this equivalently with an assignment instead of initialization would look like:
int *q;
q = 8;
So you see it doesn't make sense. (and, isn't allowed of course -- an int is not a pointer)
Just to be sure, if you write:
int *q;
*q = 8;
this is syntactically correct, but undefined behavior. Your pointer doesn't point to an object of type int, it is uninitialized and probably pointing to some invalid location. Writing there, anything could happen.
Because the types don't match.
The 6 itself is not a value of pointer type, it's an integer so it cannot be directly stored in a pointer.
When you do *q = 6 the * dereferences the pointer, so the type becomes int (or rather an lvalue int, i.e. something that can be assigned to).
Here, assign the value 8 to an object of type int*. It means q points on address 8 on memory.
int *q = 8;
Is equivalent to:
int *q;
q = 8;
Is Not equivalent to:
int *q;
*q = 8;
is illegal, as it involves constraint violation.
Related stack overflow question: Is it possible to initialize a C pointer to NULL?
A pointer variable holds an address, or 'location' of something. Thus, the pointer holds a value that is a memory address. When you say:
int *q = 6;
you are creating a pointer variable that intends to point to an int, and telling it to point to the int value stored in the address 6, which is (probably) not what you really intended.
A pointer variable should point to some memory address that contains some actual data you want to access. For example:
int x = 5;
int *q = &x;
This creates a variable (x) that contains the value 5.
the next line creates a pointer variable that contains the address of x. You have set the pointer variable 'q' to the address of the int variable 'x'.
Now you can see what is at 'x' by doing this:
int y;
y = *q;
This says "take what is pointed to by q, and store it in y". The end effect is that y will be set to 5.
int x = 5; // create variable x and set it to 5
int *q = &x; // create int pointer variable, set it to the address of x
int y; // create variable y
y = *q; // take the value pointed to by q, and store it in y
If, for example the variable x is at memory location 1234, and you looked at the value stored in 'q', it would be 1234, which is the address of x.
When you say "y = *q", you are saying "take the value stored in the address 1234, and puts that value in y". Since the memory location 1234 is 'x', and 'x' was assigned the value 5, the value 5 will be what is stored at the address 1234.
y = *q;
will take the value stored in the address 1234 and assign y to that value, thus making y 5, which was the value stored in x, which is what q 'points' to.
This could be shortened to:
int x = 5;
int *q = &x;
int y = *q;
When you write
int *q = 8; it means you declared a pointer q and initialized a pointer with the integer 8. but q being a pointer expects a address value therefore you get error stating incompatibility.
Whereas when you write
*q=8 after declaring, it means you are dereferencing the addresses pointed by q and writing a value to that location. here q points to a int so you are writing 8 a integer value to the location pointed by q. that is right. This can also lead to error at runtime if q is not initialized to point to right location.
In your first statement you are declaring and initializing the pointer to some value of type int (on the same line). In your second statement you are changing the value pointed to by a pointer. Two different things. What you have there is initialization followed by an assignment. Don't let the * confuse you.
Because it is not valid C, simple as that. Specifically, it is a constraint violation of the assignment operator, since integer to pointer or pointer to integer is not valid forms of "simple assignment" (C11 6.5.16.1).
You can convert between integers and pointers by adding an explicit cast. The result is however not guaranteed to work: pointers and integers may have different representations and there might be alignment issues.
In case of *q = 6; you assign an int to an int, which is of course perfectly fine (given that the pointer points at allocated memory somewhere).
If you re-write it like this:
int* q = 8;
*q = 6;
Then you can see the * has two different purposes.
Try
int *q = new int(8);
But working with pointers here is not normally required. If you have to use pointer, use smart pointer shared_ptr<int> or uniqe_ptr<int>.
In this case you are assigning value 8 to pointer *q and it wont work during initialization, Memory address is unique at that time not available to assign but you can set once memory block created after initialization for *q.

reassign pointer gives error

I am new to C++ , therefore please forgive me if my question seems basic, I am not able to reassign a pointer when I use the star, here is my code:
int val = 8;
int number = 23;
int *pointer = &val;
*pointer = &number; //<-- error
this gives an error: assign to int from incompatible type int. here is what I tried:
pointer = &number; // this works
therefore my question is, why is this wrong: *pointer = &number
In your code,
*pointer = &number; //<-- error
by saying *pointer, you're dereferencing the pointer, which is of type int, then you try to assign a pointer type value to it, which is not correct.
What you want to do, is to assign the address of a variable and to hold that, you want the pointer variable itself to be on the LHS of the assignment. So,
pointer = &number;
is the correct way to go.
The reason this results in an error is because you misunderstood the type of each variable.
int val = 8; // type of `val` is int
int number = 23; // type of `number` is an int
int *pointer = &val; // type of `pointer` is an int *
*pointer = &number; // type of `pointer` is int *, so type of `*pointer` is int
It doesn't work because *pointer dereferences the pointer, so you're assigning an address to a pointer, which is not what you want.
When you say
int *pointer
the * indicates that you are creating a pointer, you can think of the * as part of the data type. i.e. it's a pointer to an integer type. To reference the pointer itself (the type that stores an address in memory), you simply use the name of the pointer, just like a regular variable.
When you add the * infront, you are dereferencing the pointer. Meaning, you are accessing whatever is stored at the memory address that the pointer is pointing to, in this case an int.
Basically, pointer gives you an address in memory, *pointer gives you the int stored at that address.
int *pointer = &val;
Breaking this up actually means
int* pointer;
pointer = &val;
When you derefrence an integer pointer it becomes just an integer.When you add & to a non-pointer it becomes a pointer.So doing
is bad,because *ptr is not a pointer and &i is a pointer
int n = 0;
int *ptr = &n //good,because they are both pointers
int i = 0;
*ptr = &i //bad because only one is a pointer

c++ pointer declaration and assignment [duplicate]

This question already has answers here:
What are the barriers to understanding pointers and what can be done to overcome them? [closed]
(28 answers)
Closed 8 years ago.
int num1 = 8; //okay
int *pointer; //okay
*pointer = &num1; //NOT okay, compiler says (Error:a value of type int* cannot be
//assigned to an entity of type "int")
int num2 = 8; //okay
int *pointer = &num2; //okay
I am confused why the first part gives an error and the 2nd part doesnt, they look the same to me
In the assignment statement:
*pointer = &num1; //NOT okay
*pointer is the value that pointer points to, of type int, and &num1 is the address of num1, of type int*. As the compiler says, you can't assign a pointer to an integer.
pointer = &num1 or *pointer = num1 would both be fine, depending on whether you want to modify the pointer itself, or the value it points to.
In the declaration:
int *pointer = &num2; //okay
Despite the similar appearance to the assignment statement, this initialises pointer not *pointer. It declares pointer to be a pointer, of the same type int* as &num2.
Remove the * in third line. It returns the value stored at position/address currently stored in variable pointer and interprets it as int.
The operator & gives a pointer to the variable over which is acting.
&num1 is a pointer to int (since num1 has type int) which points to the address of num1.
The error message is very clear: The expression *pointer is of type int and the expression &num1 is of type int*. Those two types are not compatible (you try to assign a pointer to a non-pointer).
When you use the dereference operator * on a pointer, you get what the pointer is pointing to, and if you use the address-of operator & you get the address of (i.e. pointer to) something.
To make pointer point to a variable, then just assign to it:
pointer = &num1;
int *pointer = &num2;
is the same as
int *pointer;
pointer = &num2;
not
int *pointer;
*pointer = &num2;
The following is more of a general description rather than a direct answer to your question...
If you declare a variable of some type, then you can also declare another variable pointing to it.
For example:
int a;
int* b = &a;
There are two ways to "look at" variable b (that's what probably confuses most beginners):
You can consider b as a variable of type int*.
You can consider *b as a variable of type int.
Hence, some programmers would declare int* b, whereas others would declare int *b.
But the fact of the matter is that these two declarations are identical (the spaces are meaningless).
You can use either b as a pointer to an integer value, or *b as the actual pointed integer value.
You can read the pointed value (e.g., int c = *b) and write the pointed value (e.g., *b = 5).