Last time I wrote about pointers I think the real use for then wasn't clear. I think now it can start to make more sense.
But before get to point I want, more theory makes necessary :( !
Pointer arithmetic
With normal numeric variables the result of simple operations like addition or subtraction are quite predictable if we know the contents of such variables. However this rule doesn't apply for pointers.Pointers don't store numbers, but memory addresses. So if a pointer points to the mem. address 0x98456732 what happens if we add 1? The answer is, it depends! It depends on the pointer's type and how many bytes does that type needs to represent its information in the memory.
For example, on my 64 bits laptop using Visual Studio, a int variable has a size of 4 bytes, a double, 8 bytes while a char only 1 byte.
So when summing or subtracting pointers, this must be taken into account. Lets have a look in one example:
#include "stdafx.h"
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
1 int x = 10;
2 int *ptr = &x;
3
4 int address = (int)ptr;
5 printf("\nThe pointer points to %X == %X\n", ptr, address);
6
7 ptr++;
8
9 int difference = ((int)ptr) - address;
10
11 printf("%d bytes were added to %X\n", difference, address);
}
In this program at line 1 an int variable is declared and initialized with 10. In the line 2 I declared the pointer and initialized it with the address of x. Then at line 4 the address of x is assigned as a normal integer to the variable address. The printf at line 5 shows that the value stored in ptr and address are the same. Finally at line 7 the pointer is incremented by 1 unit! So now what's the value of the pointer? The answer is: the new value is equal to the original memory address plus 4! What lines 9 and 11 do is just proving what I'm saying. But why 4?
Let's call the memory address number being pointed by ptr as addr_number. The new address number obtained after the addition can be thought as:
addr_number + 1* sizeof(int) == addr_number + 1*4 == addr_number + 4So for every arithmetic operation with pointers, we have to consider the size of the type which the pointer was declared. The same applies for subtraction. About multiplication and division, I've never seen or used it in practice but I guess the same logic applies.
No comments:
Post a Comment