3

Let's take the following example where we swap the values of a and b.

void swap(int* a, int* b) {
    // remember, a and be are both memory addresses now!
    printf("The address of a is: %p\n", a);
    printf("The address of address-of a is: %p\n", &a);
    int tmp = *a;
    *a=*b;
    *b=tmp;
}

The printout gives me:

The address of a is: 0x7ffd36e62d08
The address of address-of a is: 0x7ffd36e62cd8

What exactly does the second printf statement tell us? For example:

int a = 4;
&a; // address-of a
int* b; = &a;
b; // address-of a
*b; // value-of a
&b; // address-of ...?

Is that just the location of the memory address on the stack?

carl.hiass
  • 1,526
  • 1
  • 6
  • 26

3 Answers3

3

To further expand on Deduplicator's answer, I'd change your printf's to:

printf("The _value_ of a is: %p\n", (void*)a);
printf("The address of a is: %p\n", (void*)&a);

(See this question for why you should cast to void*).

a is a pointer, and has value just like anything else, such as an int or a double. The only "difference" is, the value of a is an address. Everything in C is pass-by-value, so when you pass the pointer a to this function, a local copy of its value is made in the function. The pointer value is an address which points to an int.

yano
  • 4,827
  • 2
  • 23
  • 35
2

Is that just the location of the memory address on the stack?

That's correct.

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
2

The code should be:

printf("The address a is: %p\n", a);
printf("The address of a is: %p\n", &a);

a is a completely normal object, whose type is pointer to int.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118