Section 5.3 Dereferencing#
Adapted from: “Beej’s Guide to C Programming” by Brian (Beej Jorgensen) Hall: Beej’s Guide to C Programming: 5.3 Dereferencing
Brian (Beej Jorgensen) Hall Website
Program that Demonstrates Dereferencing a Pointer#
#include <stdio.h>
int main(void)
{
int i;
int *p; // this is NOT a dereference--this is a type "int*"
p = &i; // p now points to i, p holds address of i
i = 10; // i is now 10
*p = 20; // the thing p points to (namely i!) is now 20!!
printf("i is %d\n", i); // prints "20"
printf("i is %d\n", *p); // "20"! dereference-p is the same as i!
}
Explanation of the Above Code#
The program demonstrates the concept of dereferencing a pointer in C.
The variable
i
is declared as an integer.The variable
p
is declared as a pointer to an integer (int *p
).The address of
i
is assigned top
using the address-of operator (&
).The value of
i
is set to10
.The value pointed to by
p
is set to20
using the dereference operator (*p
).Finally, the program prints the value of
i
and the value pointed to byp
, both of which are20
.The dereference operator (
*
) is used to access the value stored at the address pointed to byp
.The output of the program will be:
i is 20
i is 20
This shows that dereferencing
p
gives the same value asi
, sincep
points toi
.
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_3_dereferencing section_5_3_dereferencing.c")
exec_status = os.system("./section_5_3_dereferencing")
i is 20
i is 20