Adapted from: “Beej’s Guide to C Programming” by Brian (Beej Jorgensen) Hall: Beej’s Guide to C Programming: 6.6.1 Arrays and Pointers: Getting a Pointer to an Array
Program for Demonstrating Getting a Pointer to an Array¶
#include <stdio.h>
int main(void)
{
int a[5] = {11, 22, 33, 44, 55};
int *p;
//p = &a[0]; // p points to the array
// Well, to the first element, actually
p = a; // p points to the array, but much nicer-looking!
printf("%d\n", *p); // Prints "11"
}Explanation of the Above Code¶
This C program demonstrates how pointers can be used to access elements of an array. Here’s a breakdown of the code:
Code Explanation:¶
#include <stdio.h>Includes the standard input/output library to use functions like
printf.
int main(void)The entry point of the program.
int a[5] = {11, 22, 33, 44, 55};Declares an integer array
awith 5 elements and initializes it with the values{11, 22, 33, 44, 55}.
int *p;Declares a pointer
pof typeint. This pointer will be used to point to elements of the array.
// p = &a[0]; // p points to the array
// Well, to the first element, actuallyThis line (commented out) shows how
pcan be assigned the address of the first element of the array using&a[0].
p = a; // p points to the array, but much nicer-looking!This assigns the base address of the array
ato the pointerp. In C, the name of an array (e.g.,a) is equivalent to the address of its first element (&a[0]), so this is a shorthand way of pointingpto the first element of the array.
printf("%d\n", *p); // Prints "11"The
*pdereferences the pointerp, accessing the value stored at the memory location it points to. Sinceppoints to the first element of the array (a[0]),*pevaluates to11, which is printed to the console.
Key Concepts:¶
Array and Pointer Relationship:
The name of an array (e.g.,
a) is a pointer to its first element.p = ais equivalent top = &a[0].
Dereferencing a Pointer:
The
*operator is used to access the value at the memory address stored in the pointer.
Output:
The program prints
11, which is the first element of the array.
This program is a simple demonstration of how pointers can be used to access and manipulate array elements in C.
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_6_6_1_getting_a_pointer_to_an_array section_6_6_1_getting_a_pointer_to_an_array.c")exec_status = os.system("./section_6_6_1_getting_a_pointer_to_an_array")11