🎓 A1Learner
🔍
0 of 50 lessons completed

C Memory Address

An address is the place where a variable lives in memory. The & operator gives the address of a variable.

Two variables, two places

age and score live at different places. The comparison prints 0, which means not the same place.

#include <stdio.h>

int main() {
  int age = 25;
  int score = 10;
  printf("%d\n", (&age == &score));
  return 0;
}

Ask the same question twice

The same comparison runs twice. Both prints show 0, so an address does not change between asks.

#include <stdio.h>

int main() {
  int age = 25;
  int score = 10;
  printf("%d\n", (&age == &score));
  printf("%d\n", (&age == &score));
  return 0;
}

An address in a test

The test asks whether two addresses are the same place. They are not, so the second line prints.

#include <stdio.h>

int main() {
  int age = 25;
  int score = 10;
  if (&age == &score) {
    printf("Same\n");
  } else {
    printf("Different\n");
  }
  return 0;
}

Example

#include <stdio.h>

int main() {
  int apples = 5;
  int oranges = 8;
  printf("%d\n", (&apples != &oranges));
  printf("%d\n", (&apples == &oranges));
  printf("%d\n", (&apples != &oranges));
  return 0;
}

Key points

  • Every variable lives at one place in memory.
  • That place is called the address of the variable.
  • The & operator gives the address of a variable.
  • &age gives the address of age.
  • Two different variables live at two different places.
  • Asking for the address of the same variable twice gives the same result.
  • Comparing two addresses with == tells whether they are the same place.

Three comparisons print. The first asks whether apples and oranges live at different places, so it prints 1. The second asks whether they live at the same place, so it prints 0. The third asks the first question again, and it prints 1 again, so the answer does not change.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which operator gives the address of a variable?