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.
Related
If i want to give a value to int *num2, how would i do this ?
#include <stdio.h>
int main(int argc, const char * argv[]) {
// insert code here...
struct az {
int num1;
int *num2;
};
struct az test;
test.num1 =20;
printf("\n %d",test.num1);
return 0;
}
int *num2; is a pointer to some place in the memory that contains an int value. Since you just declare a pointer without any memory allocating, it is simply points to nothing (or random place).
You have to allocate memory then assign a value to this memory:
test.num2 =new int(20);
However, do not forget to delete this allocated memory when you finish:
delete test.num2;
The real question here, do you really want that pointer here? probably not.
You can assign num2 in the same way as num1. Of course, since it's not an int but an int*, you can't assign 20 to it - you can assign the address of some int variable instead:
struct az {
int num1;
int *num2;
};
struct az test;
test.num1 = 20;
int i;
test.num2 = &i;
To assign a value to the integer that test.num2 points to, you must de-reference the pointer with an asterisk, like so:
test.num2 = new int(20); // Allocates memory and sets the pointer to this memory
*(test.num2) = 10; // Assign a value of 10 to the int that test.num2 points to
To assign an address to the pointer, you must either assign another pointer to it, or assign it's value by referencing an int with an ampersand:
test.num2 = new int(20); // Allocates memory and sets the pointer to this location
int *ptr = new int(10);
delete test.num2; // Free memory that test.num2 pointed to
test.num2 = ptr // Makes test.num2 point to the same int as ptr
int x = 10;
test.num2 = &x; // Makes test.num2 point to x
In your example num2 is typically used as a pointer to a dynamically allocated array. However, neither num2 nor num1 is a good name in this case. Let's instead declare our dynamic array type as a record with the fields length and items:
struct Array {
int length;
int *items;
};
typedef struct Array Array;
If we have a variable a of type Array, before we can assign values to its elements we must first allocate memory for the array. In C this is typically done with the function malloc. This function, however, is rather error prone to use so it's a good idea to define a macro function which simplifies memory allocation:
#define NEW_ARRAY(ptr, n) (ptr) = malloc((n) * sizeof (ptr)[0])
After having called NEW_ARRAY we can assign values to the array:
int length;
Array a;
length = 20;
a.length = length;
NEW_ARRAY(a.items, length);
a.items[0] = 37;
a.items[1] = 19;
...
When we are done with the array we can release the memory used by the elements:
free(a.items);
So I am trying to understand pointers and references.
Lets say we have the following:
int val = 100;
int *ip = &val;
Why is that not the same as simply pointing to val like this:
int val = 100;
int *ip = val;
Neither one of your two examples contains a pointer to reference:
The first example has a pointer to int, properly initialized using the address-of operator &
The second example has a pointer to int, improperly initialized to the value of val itself
Generally, you do not assign values to pointers directly: normally, you want an address-of operator, an implicit pointer conversion, or some pointer arithmetic. Although assigning a well-known address on specific hardware is also possible, compiler toolchains often provide ways to keep this outside of your program. Hence, if you see an assignment int *ip = 100 it's almost certainly incorrect.
If you want a reference, declare it like this:
int val = 100;
int &ref = val;
Now you can make a pointer to that reference, like this:
int *ipRef = &ref;
Since ref represents an alias for val, ipRef would have the same value as ip from your example (demo).
Easy way to understand why they are not the-same if you do this your self.
int val = 100;
cout<<val<<endl;
You shoud get 100 as output.
Now try:
int val = 100;
cout<<&val<<endl;
You should get a 0x7ffc201cab0c or something similar as the outout.
If you access val with the "&", you are accessing the memory address of it.
If you access val without the "&", you are accessing the value of it.
Therefore if you do
int val = 100;
int *ip = val;
you will should get a warning or an error but assuming that you want to see it compile so you can figure out what would happen, this is what it you should do:
int val = 100;
int *ip;
*ip = val;
This is the-same as the previous code except that it will compile. You are creating a pointer and assigning a value to the pointer instead of assigning a memory address to it. The code is valid but has a run-time error. The pointer ip is NOT pointing anywhere before you assigned value to it.
To make it work properly, you can do:
int val = 100;
int *ip = new int;
*ip = val;
Now, you have a pointer with a memory address. The value of that pointer is val which is 100. That's the value NOT the memory address.
To conclude this, pointer must be initialized or it will have undefined behavior or even crash. You use the ref sign (&) or the new keyword to initialize pointers then you can assign assign values to it.
int val = 100;
int *ip = new int; //Create a new pointer and initilize it with a new memory address
*ip = val; //Assign the value from val(100) to the pointer
OR
int val = 100;
int *ip = &val; //Create a new pointer and initialize it by making it point to existing address of **val**
*ip = 200; //change the value in the **memory addresss to **200**
Now val changes to 200 too.
int otherValue = 500;
*ip = otherValue ; //change the value in the **memory address** to 500
Now val changes to 500 too.
CHANGE MEMORY ADDRESS WHERE ip IS POINTING
You can also change the memory address anytime.
Lets make p point to otherValue.
*ip = &otherValue; //Point p to otherValue memory address not value
*ip = 5; //Change the value of p to 5(no memory address change)
Now otherValue has 5 as the value. p points to otherValue memory address.
val is an integer, so you can not assign an int to a pointer that points to an int because is not the valid value, you will need the address (obtained with the & operator)
Because pointers and integers are different data types.
int *ip = &val;
This initialises one int* with another int* (the value obtained by taking the address of val).
int *ip = val;
This is an attempt to initialise an int* with an int, which is not allowed.
Note that your code examples do not contain any references.
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
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
Can assign a pointer to a value on declaration? Something like this:
int * p = &(1000)
Yes, you can initialize pointers to a value on declaration, however you can't do:
int *p = &(1000);
& is the address of operator and you can't apply that to a constant (although if you could, that would be interesting). Try using another variable:
int foo = 1000;
int *p = &foo;
or type-casting:
int *p = (int *)(1000); // or reinterpret_cast<>/static_cast<>/etc
What about:
// Creates a pointer p to an integer initialized with value 1000.
int * p = new int(1000);
Tested and works. ;-)
There are two things not clear in the question to me. Do you want to set the pointer to a specific value (i.e address), or do you want to make the pointer point to some specific variable?
In the latter case, you can just use the address-of operator. The value of the pointer is then set to the address of some_int_variable.
int *p = &some_int_variable;
*p = 10; // same as some_int_variable = 10;
Note: What follows is evil changing of the pointer's value manually. If you don't know whether you want to do that, you don't want to do it.
In the former case (i.e setting to some specific, given address), you can't just do
int *p = 1000;
Since the compiler won't take the int and interpret it as an address. You will have to tell the compiler it should do that explicitly:
int *p = reinterpret_cast<int*>(1000);
Now, the pointer will reference some integer (hopefully) at address 1000. Note that the result is implementation defined. But nevertheless, that are the semantics and that is the way you tell the compiler about it.
Update: The committee fixed the weird behavior of reinterpret_cast<T*>(0) that was suggested by a note and for which i provided a workaround before. See here.
Um. I don't think you can take a non-const address of a constant like that.
but this works:
int x = 3;
int *px = &x;
cout << *px; // prints 3
or this:
const int x = 3;
const int *px = &x;
const int *pfoo = reinterpret_cast<const int*>(47);