Pointers and Arrays in C

Learn how pointers and arrays work together in C on Debian 12 using Vim. Understand their relationship, how to traverse arrays using pointers, and practical examples.

Pointers and Arrays in C

In C, pointers and arrays are closely related. The name of an array acts like a constant pointer to its first element. This relationship allows pointers to be used for traversing and manipulating arrays efficiently.

Array Name as Pointer

When you use an array name in an expression, it is converted to the address of its first element. Example:
int numbers[3] = 10, 20, 30;
printf(\\"%p\\", numbers); // address of first element
printf(\\"%p\\", &numbers[0]); // same address

Accessing Array Elements with Pointers

Pointers can be incremented to move through array elements without using square brackets.
int *ptr = numbers;
printf(\\"%d\\", *ptr); // first element
ptr++;
printf(\\"%d\\", *ptr); // second element

Complete Example

The following program demonstrates traversing an array using a pointer instead of array indexing.
#include 

int main() 
    int numbers[5] = 10, 20, 30, 40, 50;
    int *ptr = numbers;

    printf(\\"Traversing array using pointers:\\\
\\");
    for(int i = 0; i < 5; i++) 
        printf(\\"Element %d: %d\\\
\\", i, *ptr);
        ptr++;
    

    return 0;

Step-by-Step Explanation

  • numbers – Represents the address of the first element.
  • ptr = numbers – Assigns the starting address of the array to the pointer.
  • *ptr – Dereferences the pointer to get the value.
  • ptr++ – Moves the pointer to the next element in the array.

Running the Program

Use the following commands in Debian 12 to compile and run:
gcc pointers_and_arrays.c -o pointers_and_arrays
./pointers_and_arrays

Expected Output

Traversing array using pointers:
Element 0: 10
Element 1: 20
Element 2: 30
Element 3: 40
Element 4: 50

Conclusion

Pointers provide a flexible way to work with arrays. By understanding their relationship, you can write more efficient and readable C code.

Subscribe to Our YouTube for More

Download as PDF

https://blog.arashtad.com/updates/pointers-and-arrays-in-c/?feed_id=13629&_unique_id=689f8f7cd2193

Comments

Popular posts from this blog

Why Smart Contracts Are Revolutionary? (Smart Contracts Use Cases)

A Quick Guide to Tron Network Interaction using Python.

#36 Multi-Signature Wallet Smart Contract (Part 3)