- #26
Mark44
Mentor
- 34,539
- 6,234
The compiler always knows the size of an int, a char, a float, and so on.Do you mean when I do cout << *(pInt + index), compiler know each integer is 4 byte so it knows jump by 4 every time index++ and display correctly.
Read this and memorize it.But compiler knows characters are ONE BYTE. So when I do Cr[ind] = *(pChar + ind) will only go to the next location. Since the content of memory is 0x31 0x00 0x00 0x00 0x32 0x00 0x00... So it read as {1, 0, 0, 0, 2}?( as shown in the first 5 highlighted bytes).
In C or C++,
Pointer arithmetic is scaled by the size of the type pointed to.
This means that the result of any valid arithmetic expression involving a pointer variable will depend completely on the type of thing being pointed to.
Suppose that pChar, pShort, pFloat, and pDouble are all declared as pointers to the type that is part of their name. I.e.,
char* pChar;
and so on. All four types being pointed to are different sizes: 1 byte, 2 bytes, 4 bytes, and 8 bytes, respectively.
C++:
int Arr[] = {1, 2, 3, 4, 5, 6}
char* pChar = reinterpret_cast<char*>(Arr;)
short* pShort = reinterpret_cast<short*>(Arr);
float* pFloat = reinterpret_cast<float*>(Arr);
double* pDouble = reinterpret_cast<double*>(Arr);
For the sake of argument, suppose that the array starts at location 0x1000. (That's not where it will be, but bear with me.)
Consider the expressions pChar + 1, pShort + 1, pFloat + 1, pDouble + 1.
The value of pChar + 1 would be 0x1001.
The value of pShort + 1 would be 0x1002.
The value of pFloat + 1 would be 0x1004.
The value of pDouble + 1 would be 0x1008.
This is related to what pbuk was talking about in post #23 above. If you add 1 to a pointer, the resulting address will be higher than the value in the pointer by as many bytes as the type being pointed to.
In other words, Pointer arithmetic is scaled by the type being pointed to.
The same idea holds if you add any integer value to a pointer, subtract any integer value from a pointer, of subtract one pointer from another (same types of pointers).
With cout <<, pChar is considered to be a string, and pChar + 4*ind is likely the address of a null character or a non-printing ASCII code, so no output. When the debugger is running, you can evaluate any expression that involves variables that are in scope using the Immediate window.But, when I do cout << (pChar + 4*ind); it will not display the address like cout << (pInt + index).
They are different. Still missing something.
Debug --> Window --> Immediate
Just type the expression you want to evaluate, and its value will be shown in the window.
Last edited: