Section 5.1 Memory and Variables#

Adapted from: “Beej’s Guide to C Programming” by Brian (Beej Jorgensen) Hall: Beej’s Guide to C Programming: 5.1 Memory and Variables

Brian (Beej Jorgensen) Hall Website

Program that Demonstrates Printing out the Address of a Variable#

#include <stdio.h>

int main(void)
{
    int i = 10;

    printf("The value of i is %d\n", i);
    printf("And its address is %p\n", (void *)&i);
}

Explanation of the Above Code#

The program above demonstrates how to print out the address of a variable in C. The program does the following:

  1. It includes the standard input-output library stdio.h to use the printf function.

  2. It defines the main function, which is the entry point of the program.

  3. It declares an integer variable i and initializes it with the value 10.

  4. It prints the value of i using the printf function with the format specifier %d, which is used for integers.

  5. It prints the address of i using the printf function with the format specifier %p, which is used for pointers. The address is obtained by using the address-of operator & on i. The address is cast to (void *) to match the expected type for %p.

Compile and Run Code#

Use Python to Change to Working Directory#

import os
root_dir = os.getcwd()
code_dir = root_dir + "/" + "C_Code"
os.chdir(code_dir)
build_command = os.system("gcc -o section_5_1_memory_and_variables section_5_1_memory_and_variables.c")
exec_status = os.system("./section_5_1_memory_and_variables")
The value of i is 10
And its address is 0x7fff38781a7c