What is the difference between these two declarations :
int *p = new int;
int *q;
int *p = new int;
*p = 8;
The first statement declares a new variable p to be a pointer to int and initialises it with the address returned by new int, which is a valid memory address for storing an int. The second statement assigns the value 8 to the int at the memory address pointed to by p.
int *q;
*q = 8;
Now the first statement does not initialize the pointer q, which will hence have no meaningful value. The second statement then attempts to write to a memory address which in all likelihood is not an address where such an operation is allowed and as a result the program will crash (most likely with segmentation fault).
int *p = new int;
This is a declaration. It declares a variable of type int *. The name of the variable is p. The variable is copy-initialised with the expression new int.
int *q;
This is a declaration. It declares a variable of type int *. The name of the variable is q. The variable is default initialised.
Related
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.
int main(int argc, char *argv[])
{
int *p=5,**P;
printf("%d",&P);
}
What is the difference between *p and **P?
*p is a pointer which points to an int that is equal to 5
**P is a pointer to A pointer;it is a variable that contains an address.
A pointer is a variable that contains an address. In your PC every variable is stored in a certain place in its memory. The exact place where a variable is placed is called variable's address.
With a pointer you are able to know the exact address of another variable.
Example
int c = 5; // this value of this int is stored at a certain address;
int *p = &c; // the pointer p now contains the address where 5
Keep in mind that *p is a variable too and as such is stored somewhere in the memory as well.
int **P = &p ; // a double pointer that contains the address of the pointer p
this will be a new pointer that points to the address where p is stored ( not the variable c!) –a pointer;
A single asterisks represents a pointer whereas a double asterisks represents a pointer to a pointer.
*p is an address to an int that equals 5. So somewhere in memory, there is an int that equals 5 and that pointer points to that address of that int.
**p is an address to a pointer in memory. So think of it that we have a pointer pointing to the int above, but now on top of that, we have another pointer pointing to the pointer for the int. Another way to think of it is we have an address for another address that's for the int.
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
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).
int main()
{
int a = 10;
int *p; // int *p = a; gives me an error: invalid conversion from int to int *.
// Tell me why?
*p = a; // while this runs
cout << &a <<" "<<p;
}
Secondly &a and p gives 2 different values. According to me Address of a and the value stored in pointer p should be the same?
int *p = a, interpreted literally, takes the value stored in a and tries to interpret it as a memory address to store in p. While computationally legal, C++ won't allow this without an explicit typecast, because this is normally not what you want to do.
The reason why the statement int *p = a is different from *p = a is simple: the first statement, shorthand for the following
int *p;
p = a;
is initializing the pointer, so it expects a memory address on the RHS, while the second statement is assigning a value to the location pointed to by p, so expects (in this case) an integer on the RHS.
If you want to initialize p to point to a, you can use int * p = &a or p = &a instead, where & is the address-of operator. NEVER try to dereference uninitialized pointers! You will end up touching memory in an essentially arbitrary location, which could cause a segmentation fault (resulting in crash) or start overwriting other data in your program (resulting in obscure and non-reproducible bugs).
When you run your example code, p and &a have different values precisely because p was never assigned to point to the address of a. Some short background on why you might get any nonzero value in p at all: local variables are assigned from a special region of memory known as the stack, which also stores information about function calls and return addresses. Each process has their own stack. Crucially, though, unused regions of the stack aren't really zeroed out or otherwise cleaned up before use (except maybe in debug builds, which tend to assign really obvious values like 0xCCCCCCCC or 0xBAADF00D to uninitialized pointers). If your compiler doesn't automatically set default values for you (and release builds generally won't have such automatic initialization, for efficiency's sake), what you are seeing in p is what happened to be located in the memory assigned to p before your program set up its stack frame.
int *p = a; initializes a pointer p with a which isn't a pointer (hence the error), while *p=a; assigns a to the memory pointed to by p, syntactically speaking. Also, the former is an initialization, while the latter is assignment.
Note that in your case, *p=a invokes undefined behavior, as p doesn't point to program's legal memory, i.e you have not allocated memory for p.
You store a at the address that p points to (*p). If you want to store the address of a (&a) in p, you must use
p = &a;
Using int *p = a, gives an error, because p is a int*, while a is an int. Think of it as int* p = a.
int *p = a; - This means you are declaring a variable and assinging values to it. Variable name is p and its type is int * value you are assiging is a (10) which will be assigned to p. int *p = a; is equivalent to
int *p;
p = a;
We cant assing a int value to int *.
*p = a; - This you are assing int to the *p not p. so this is fine. Before doing this dont forget to allocate memory for p other it may leads to crash(undefined behaviour) because p might have some garbage values.
I hope you are trying to assing address of a to p. In that you case you can do like below.
int a;
int *p = &a;