why address difference is 1 between two int in C program.
i've centos 7.5 in VM and practicing in c with IDE CodeBlocks. I am trying with following code. Here I am trying to subtract address of two int variables, subtraction is 1, even when manually seeing difference is 4 bytes. same with char variable address. why there is address difference is one(i.e. 1).
Code:
#include <stdio.h> |
because the length of an int is 4 bytes - try to print sizeof(int).
|
Be careful - pointer subtraction is defined only when both pointers point to the same array. It returns the difference in array indices.
Ed |
When you add 1 to a pointer, the address increases by size of the type. Subtraction works the same way. All pointer arithmetic is scaled by the type size. This is because *(p + 1) is the same as p[1].
To find the actual difference in addresses, you can cast the pointers to long integer types and then subtract. |
Strictly speaking, and depending on the optimization options selected, the addresses might be different because of "slack bytes" that may be inserted for "memory-line alignment" in the CPU. But, pointer-arithmetic as described will still work in all cases.
If you specifically need for a struct to occupy the minimum number of bytes required ("packed"), you must request it. |
Quote:
|
This will get you the 4:
Code:
diff = (void *)(&a) - (void *)(&b); Code:
diff = (char *)(&a) - (char *)(&b); |
K&R says:
The valid pointer operations are assignment of pointers of the same type, adding or subtracting a pointer and an integer, subtracting or comparing two pointers to members of the same array, and assigning or comparing to zero. All other pointer arithmetic is illegal. The "same array" requirement is not just theoretical. I have seen pointer subtraction return bogus results when the pointers are in different arrays. I suspect this happens when the address difference is not an exact multiple of the array element size. The right answer is "don't subtract pointers to different variables". Ed |
respected sir TB0ne, I didn't worked in any software company for more than 2-4 months. I had psychetric probelms. so that i could not worked in any company. I am doing my self study to teach others c and c++ in linux platform. I don't have any industrial experince. thank you.
|
Quote:
You have shown, and continue to show, no efforts of your own. You don't appear to be able to apply what you've been told, either. Have you gone back through any of your other threads??? |
All times are GMT -5. The time now is 05:53 AM. |