+ 1
Two stack variable address difference
I have two int variables on stack as below code: When i am substracting address of these two int variables , it should not be 4 or 8 instead of 1 ? https://code.sololearn.com/cWlocLTzz03J/?ref=app
5 Antworten
+ 4
Ketan Lalcheta Here's a few things to consider:
Your second code:
int x;
float y;
float z;
cout << &x - &z ;
will not compile. So it won't print anything (as you say 2).
▪︎A subtraction is allowed on pointers of the same type, this will result the difference in units of that data type size. As you get 1 on the attached code.
▪︎to get the difference of memory addresses you can cast pointers to a same size data type
cout << (long)&x - (long)&y
if long int and pointer be the same size (8 bytes on a 64bit machine). or multiply result by sizeof(type)
▪︎ subtraction of two same type pointers are allowed, addition or any other operation aren't.
▪︎it's not good nor common practice to do what you did, even proper use needs much attention to avoid bugs.
▪︎add, sub by a const is fine, note that (int *)+n jumps n*sizeof(int) bytes in memory not n bytes.
▪︎a section disassembly of your code attached, note lines 20, 25 and 26.
https://code.sololearn.com/cckplrEP9HOf/?ref=app
+ 2
when you subtract pointers, their difference represents the number of data items between the pointers. in case of int ( assuming sizeof int is four bytes on your system ), the difference between pointers that are four-bytes apart is
( 4 / sizeof( int ) ), which works out to 1.
https://www.sololearn.com/compiler-playground/cu25VVyqRZI7
+ 1
You are getting such answer because pointer arithmetic works in multiple of size of the data type the pointer is pointing to instead of raw bytes between two memory locations.
+ 1
Thanks MO ELomari , Mirielle and Arsenic
Got idea and basically pointer arithmatic is used to point elements inside array ..like arr is base address of int arr[10] and arr+1 would point to next element. Is pointer arithmatic used elsewhere ?
I believe below is not a good choice but it does print output as 2.
int x = 4;
FLOAT y = 5;
Float z = 6;
cout << &x - &z << endl;