Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C array variable & address computation

Tags:

c

int a[2][2]={{2,3},{1,6}};
printf(“%d”,&a[1][0] - &a[0][1]);

Here, a[0][1] and a[1][0] are two consecutive integer items.As each integer will take 4 bytes then it should have 4 bytes difference between them.So,answer should be 4. But I think,address subtraction is illegal.And in Dev-C++,it generates compiler error also.But the given output is 1.How come it becomes possible?

like image 425
JackSavvySparrow Avatar asked Mar 21 '26 08:03

JackSavvySparrow


2 Answers

You're doing substraction on int pointers, so you get a result in "sizeof(int) units". If you run your current code, it'll print 1, because those integers are indeed next to each other.

What you probably want to do is arithmetic on the addresses as numbers :

int a[2][2]={{2,3},{1,6}};
printf("%" PRIiPTR,(intptr_t)&a[1][0] - (intptr_t)&a[0][1]);

Casting the pointers to intptr_t (in header stdint.h) is a way to do that.

PRIiPTR is a macro (from header inttypes.h) used to output an inptr_t variable with printf.

like image 174
tux3 Avatar answered Mar 23 '26 00:03

tux3


No, it should not be 4.

Your assumption is incorrect: Pointer arithmetic is done in units of the type being pointed at (i.e. sizeof (int) here), not in bytes.

Your array looks like this in memory:

[ 2 | 3 | 1 | 6 ]

You are printing the difference between the addresses of the 1 and the 3, which are adjacent, i.e. there's exactly 1 int's worth of bytes between them.

Also, you're incorrect to print a pointer difference as if it's an int (with %d). The proper way is to use "%" PRIdPTR and cast to intptr_t.

like image 25
unwind Avatar answered Mar 23 '26 00:03

unwind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!