Kourosh23 wrote: |
---|
So you mean pointer should only point at one integer ? Then is there any way we can point a pointer to the address of an array that holds several integers ? |
Normally you would use a pointer to the first element in the array.
Arrays implicitly "decay" to pointers to the first element so you can assign the array to a pointer without doing anything special.
1 2
|
int x[] = {5, 10, 15, 20};
int *y = x;
|
But what really happens is this.
|
int *y = &x[0]; // y points to the first element in x
|
The syntax for accessing elements by index is the same for both the array and the pointer. This works because y[i] is just a neat way of writing *(y+i).
For example if you use y[2] to access the third element in the array, what happens is that you move the y pointer two steps giving you a pointer to the third element (y+2). Then the dereference operator * is used to read the value of that pointer *(y+2).
----------------------
| 5 | 10 | 15 | 20 |
----------------------
^ ^
| |
| y+2 (points to the third element in the array)
|
y (points to the first element in the array) |
Kourosh23 wrote: |
---|
I don't understand what you mean. Could you clarify the part which you say "you want ot modify the value of p (the pointer)" ? |
What I mean is that the pointer p is modified so that it points to a new location.
1 2
|
p = new int;
// p now points to the newly created int
|
If you instead had written
*p = new int;
it would have meant that you wanted to set the int that is pointed to by p equal to
new int
. This wouldn't work for two reasons.
1. *p is an int.
new int
returns a pointer to the newly created int so the return type is int*. Assigning an int* to an int doesn't make sense and wouldn't compile.
2. p is not pointing to any valid object because you deleted it on the line above so assigning a value to *p wouldn't be a good idea.
I think what confuses you is the * symbol that is used when declaring the pointer.
Note that this is not using the dereference operator. It's the same symbol but the meaning is different in this context.
You could have written the same thing in two lines as follows:
The * symbol in this context just means that p is a pointer.
You often see people write * closer to the type instead of the variable name.
The meaning is the same but it more clearly shows that * is part of the type (the type of p is int*), and it look less like a dereference operator.