Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Section 6.6.1 Arrays and Pointers: Getting a Pointer to an Array

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

Brian (Beej Jorgensen) Hall Website

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 a with 5 elements and initializes it with the values {11, 22, 33, 44, 55}.

int *p;
  • Declares a pointer p of type int. 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, actually
  • This line (commented out) shows how p can 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 a to the pointer p. 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 pointing p to the first element of the array.

printf("%d\n", *p);  // Prints "11"
  • The *p dereferences the pointer p, accessing the value stored at the memory location it points to. Since p points to the first element of the array (a[0]), *p evaluates to 11, which is printed to the console.

Key Concepts:

  1. Array and Pointer Relationship:

    • The name of an array (e.g., a) is a pointer to its first element.

    • p = a is equivalent to p = &a[0].

  2. Dereferencing a Pointer:

    • The * operator is used to access the value at the memory address stored in the pointer.

  3. 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