P12: Memory locations

Published

April 24, 2026

Goals

  • Get practice thinking about memory

Objective

Consider the following variables declarations:

char a, b, c, *s, *t, *u;

How are these laid out in memory? Write a program which includes this declaration and prints out the locations of all of these variables in memory, one line per variable.

What we want to know is how these variables are arranged in memory. How big are they? Are they in order? Are they tightly packed? Write your observations into the comment before this function.

Now, let’s make use of that knowledge. Add the following lines of code to your program:

  a = 'A';
  b = 'B';
  c = 'C';
  s = &a;
  t = &b;
  u = &c;

As you should be able to tell, this loads a, b, and c with ‘A’, ‘B’, and ‘C’, respectively. It also sets s, t, and u to point at a, b, and c. Add another printf to your program that prints out the contents of each one of those variables (which means you should give me addresses for the pointers, not what they are pointing at) again, one variable per line. You would write this:

 printf("a: %c\nb: %c\nc: %c\ns: %p\nt: %p\nu: %p\n", a,b,c,s,t,u);

However, I want you to demonstrate what you learned above. So, the only variable you are allowed to use in the parameter list of the printf is s.

Hint: you can use both the contents and the address of s in your solution, and, of course, you can include s or its address in mathematical expressions with constants.

Requirements

  • At the top of your C file, there should be a multiline comment that includes your name, the date, instructions for compiling the code and instructions for running it
  • There are 12 lines of output
  • The first 6 lines are of the form a: 0x16d5be7cf, with the name of the variable and its location in memory
  • The second 6 lines print out the contents of the variables in the same form
  • The only variable used to print the second set of outputs is s
  • There should be a comment containing a description of how the six variables are laid out in memory
  • On a valid run, your program should return 0 (this is usually how we indicate “completed with no errors”)

Submission

Upload your .c file to Gradescope.