Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Address in C: &(number)

Tags:

c

I don't understand the output of this program:

int arr[]={1,7,4,2,5,8};
int x=(&(arr[arr[1]-arr[4]])-arr);
printf("%d" ,x);

arr[arr[1]-arr[4]] is equal to 4. What does it mean &(4)? Why does it print 2?

like image 675
user1479376 Avatar asked Jul 01 '12 19:07

user1479376


People also ask

What is address and pointer in C?

Pointers in C are used to store the address of variables or a memory location. This variable can be of any data type i.e, int, char, function, array, or any other pointer. The size of the pointer depends on the architecture.

Why do we use address in C?

Because you want scanf() to take in input, and write that data to the memory location of the variable you need the data to be in. & means you are passing the memory address of that variable.

What is an address in a memory?

In computing, a memory address is a reference to a specific memory location used at various levels by software and hardware. Memory addresses are fixed-length sequences of digits conventionally displayed and manipulated as unsigned integers.

What data type is address?

An address is stored in a compound type known as a pointer type.


2 Answers

arr[1] - arr[4]

This is just as it looks. 7 - 5 = 2, so let's replace that with 2:

arr[2]

That's also just as it looks. 4. The & takes its address, which will be two ints offset from the beginning of the array, which is arr.

&(arr[2]) - arr

That subtracts arr, so you're left with the offset of arr[2] from arr, which is two ints. There you go.

Here's a reduced example.


In case you were expecting it to be 8, well, that's just how pointer arithmetic is. Casting them both to unsigned int:

(unsigned int)&arr[2] - (unsigned int)arr

will yield 8, at least when an int is four bytes. (Demo)

like image 163
Ry- Avatar answered Oct 24 '22 05:10

Ry-


Look at minitech's answer for showing how the print value of "2" can be deduced.

However, I think that in your case you just misunderstood how the & operator works. Yes, arr[arr[1]-arr[4]] is 4, but that does not mean that &(arr[arr[1]-arr[4]]) is doing &4; it's doing &(arr[2]); and it's taking the address of arr[2], not the value of arr[2], which is 4.

like image 21
houbysoft Avatar answered Oct 24 '22 05:10

houbysoft