Reputation: 1232
I have searched for a while now and most results didn't help a lot because almost all index and pointer related questions are headed towards arrays. I have a conceptual problem visualizing what the index of a pointer might be. This example function takes argv[1]
from arguments:
unsigned long pointerfun(const char* p){
int* ip; // Declare an int pointer ip
ip = (int*)p; // Initialize the pointer with the value of p cast to an int pointer
int i;
int res=0;
for(i=0; i<5; i++){ // Loops from 0 to 4
res += ip[i]; // ...incrementing res by ip[0], ip[1],...
}
return res;
}
So I realize a pointer points to a memory location, in my example code ip points to whatever memory address is entered as p. But in my understanding, pointers are no data structures, so I have no idea what ip[0,1,...,4]
might reference to.
Would be really great if someone more prudent could illuminate me here.
Upvotes: 1
Views: 2511
Reputation: 409404
To help you better understand, lets try and make it more "graphical"...
Memory is a series of consecutive locations where values can be stored. After your assignment ip = (int*)p
you can look at ip
like this:
ip | v +-------+-------+-------+---- | ip[0] | ip[1] | ip[2] | ... +-------+-------+-------+---- ^ ^ ^ ^ | | | | 100 104 108 112
Since ip
is a pointer, there is really no specific end to the "array" it points to, the end you have to keep track of yourself.
Now when it comes to addressing, for simplicity's sake lets say that ip
points to the address 100
, that means that the contents of the variable ip
is 100
. Lets also say that sizeof(int) == 4
.
Then when you do ip[2]
it's the same thing as doing *(ip + 2)
, then you are adding 2 * sizeof(int)
(i.e. 8
) as byte offset to the pointer, and get address 108
which is then dereferenced giving you the contents of ip[2]
(whatever that might be).
Now for a little curiosity and to "really fry your noodle": Thanks to the commutative property of addition, the expression *(ip + i)
is of course the same as *(i + ip)
which leads to the weird but valid transformation that ip[i]
is the same as i[ip]
.
Upvotes: 4
Reputation: 2303
ip[n]
is the same as *(ip+n)
.
You can see ip[n]
as the n-th integer
away from the integer
at address ip
. Usually this type of syntax occurs in an array.
Also, if you did not allocate memory properly you might run into some run-time errors / invoke undefined behaviour.
Upvotes: 1