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;
Related
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.
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.
I'm new to programming and I'm trying to wrap my head around the idea of 'pointers'.
int main()
{
int x = 5;
int *pointerToInteger = & x;
cout<<pointerToInteger;
}
Why is it that when I cout << pointerToInteger; the output is a hexdecimal value, BUT when I use cout << *pointerToInteger; the output is 5 ( x=5).
* has different meaning depending on the context.
Declaration of a pointer
int* ap; // It defines ap to be a pointer to an int.
void foo(int* p); // Declares function foo.
// foo expects a pointer to an int as an argument.
Dereference a pointer in an expression.
int i = 0;
int* ap = &i; // ap points to i
*ap = 10; // Indirectly sets the value of i to 10
A multiplication operator.
int i = 10*20; // Needs no explanation.
One way to look at it, is that the variable in your source/code, say
int a=0;
Makes the 'int a' refer to a value in memory, 0. If we make a new variable, this time a (potentially smaller) "int pointer", int *, and have it point to the &a (address of a)
int*p_a=&a; //(`p_a` meaning pointer to `a` see Hungarian notation)
Hungarian notation wiki
we get p_a that points to what the value &a is. Your talking about what is at the address of a now tho, and the *p_a is a pointer to whatever is at the &a (address of a).
This has uses when you want to modify a value in memory, without creating a duplicate container.
p_a itself has a footprint in memory however (potentially smaller than a itself) and when you cout<<p_a<<endl; you will write whatever the pointer address is, not whats there. *p_a however will be &a.
p_a is normally smaller than a itself, since its just a pointer to memory and not the value itself. Does that make sense? A vector of pointers will be easier to manage than a vector of values, but they will do the same thing in many regards.
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;
So in essence, for each basic type, we also have a corresponding pointer type.
For example: short and short*.
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 people 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 get (read) the pointed value: int c = *b.
And you can set (write) the pointed value: *b = 5.
A pointer can point to any memory address, and not only to the address of some variable that you have previously declared. However, you must be careful when using pointers in order to get or set the value located at the pointed memory address.
For example:
int* a = (int*)0x8000000;
Here, we have variable a pointing to memory address 0x8000000.
If this memory address is not mapped within the memory space of your program, then any read or write operation using *a will most likely cause your program to crash, due to a memory access violation.
You can safely change the value of a, but you should be very careful changing the value of *a.
yes the asterisk * have different meanings while declaring a pointer variable and while accessing data through pointer variable. for e.g
int input = 7;
int *i_ptr = &input;/*Here * indicates that i_ptr is a pointer variable
Also address is assigned to i_ptr, not to *iptr*/
cout<<*i_ptr;/* now this * is fetch the data from assigned address */
cout<<i_ptr;/*it prints address */
for e.g if you declare like int *ptr = 7; its wrong(not an error) as pointers ptr expects valid address but you provided constant(7). upto declaration it's okay but when you go for dereferencing it like *ptr it gives problem because it doesn't know what is that data/value at 7 location. So Its always advisable to assign pointers variable with valid addresses. for e.g
int input = 7;
int *i_ptr = &input;
cout<<*i_ptr;
for example
char *ptr = "Hello"; => here * is just to inform the compiler that ptr is a pointer variable not normal one &
Hello is a char array i.e valid address, so this syntax is okay. Now you can do
if(*ptr == 'H') {
/*....*/
}
else {
/*.... */
}
I want to know the statement below is not valid,
int* p;
*p = 3;
but this statement below is
int* p; int a;
a = 9;
p = &a;
*p = 3;
Why cannot I give *p a value before giving it an address but can give it after assigning an address. Thanks
A pointer is just a special type of variable that holds a memory address as its value. Before being initialized, it could possibly point to any random memory address.
Dereferencing a pointer (using the *p = 3 syntax) is telling the computer to go to the memory address pointed to by p, and store the value 3 in that location.
So it should be obvious that without a valid memory location, this is problematic. Here's one possible way of obtaining a valid memory address via allocation:
int *p = new int;
*p = 3;
The first line does two things: 1) allocates memory on the heap for an int, and 2) sets the value of pointer p to the address of the allocated memory.
Without being initialized to point to an address, a pointer will contain some trash address, which is what you attempt to write to in the first example. To be valid, it is essential that the pointer references some valid memory that you own, which requires that you set it to an address.
I thought the following codes were correct but it is not working.
int x, *ra;
&ra = x;
and
int x, ra;
&ra = x;
Please help me if both of these code snippets are correct. If not, what errors do you see in them?
Your both expressions are incorrect, It should be:
int x, *ra;
ra = &x; // pointer variable assigning address of x
& is ampersand is an address of operator (in unary syntax), using & you can assign address of variable x into pointer variable ra.
Moreover, as your question title suggests: Assigning int value to an address.
ra is a pointer contains address of variable x so you can assign a new value to x via ra
*ra = 20;
Here * before pointer variable (in unary syntax) is deference operator gives value at the address.
Because you have also tagged question to c++ so I think you are confuse with reference variable declaration, that is:
int x = 10;
int &ra = x; // reference at time of declaration
Accordingly in case of the reference variable, if you want to assign a new value to x it is very simply in syntax as we do with value variable:
ra = 20;
(notice even ra is reference variable we assign to x without & or * still change reflects, this is the benefit of reference variable: simple to use capable as pointers!)
Remember reference binding given at the time of declaration and it can't change where pointer variable can point to the new variable later in the program.
In C we only have pointer and value variables, whereas in C++ we have a pointer, reference and value variables. In my linked answer I tried to explain differences between pointer and reference variable.
Both are incorrect.
When you declare a pointer, you assign it the address of a variable. You are attempting the other way round. The correct way would be:
int x,*ra;
ra = &x;
Both of those causes, in the way you have them in your question, undefined behavior.
For the first, you don't initialize the pointer, meaning it points to a random location (or NULL if the variable is global).
For the second, you try to change the address the variable is located at, which (if it even would compile) is not allowed.
Here's some annotated code:
int main () {
// declare an int variable
int x = 0;
// declare a pointer to an int variable
int *p;
// get the memory address of `x`
// using the address-of operator
&x;
// let `p` point to `x` by assigning the address of `x` to `p`
p = &x;
// assign `x` a value directly
x = 42;
// assign `x` a value indirectly via `p`
// using the dereference operator
*p = 0;
// get the value of `x` directly
x;
// get the value of `x` indirectly via `p`
// using the dereference operator
*p;
}
Note that dereferencing a pointer that doesn't point to a valid object of the specified type is not allowed.
So you normally shouldn't do things like the following (unless you really know what you are doing):
*(int*)(12345) = 42; // assign an integer value to an arbitrary memory address
Here is my 2 cent.
If you are going onto understanding pointer in C. First make the distinction between * the operator and * the type qualifier/specifier.
See that in C * is a syntaxique element that can plays both role but never at the same time. A type qualifier:
int a;
int * c = &a;
int * my_function_returning_pointer();
And for getting the proper int. As an operator. ( *c is an alias of a)
*c = 9;
I admit that is quite confusing and can trap a lot of beginner. Make sure that you recognize when * is used as an operator or when it is used as a type qualifier.
The same things apply to & although it is less often used as type qualifier.
int & f = returning_a_reference();
int my_function( int & refParam);
It is more often use for getting the address of an object. Thus it is used as an operator.
c = &f;
case 1:
int x,*ra;
&ra = x;
it is wrong in c, because in c we can point to a memory location by using a pointer ( i.e *ra in your case ). this can be done as fallows
int x, *ra; x ---------
ra=&x; ra --->1000 | value |
----------
NOTE : with out initializing a variable we can't use pointer to hold the address of that variable, so you better to first initialize variable, then set pointer to that memory location.
int x, *ra;
x=7;
ra=&x;
Fallowing may be helpful to you:
problems(mistake we do ) in handling pointers :
1.)
int a ,*p;
p=a; // assigning value instead of address. that leads to segmentation fault at run time.
2)
int a, *p;
&p=a; // look at here wrong assignment
3)
char *p="srinivas"
strcat(p, "helo" ) ; // we cant add a substring to the constant string.
4) int a=5, *p;
p=5; // the pointer here will points to location 5 in the memory, that may damage whole system, be care full in these type of assignments.