C documentation V1 Help

Array Pointers

Array pointers in C provide a flexible mechanism for manipulating arrays efficiently using pointers. This section explores the relationship between arrays and pointers, focusing on using pointers to navigate and manipulate array elements.

Pointer Declaration for Arrays

  • Pointers can be used to point to the beginning of an array:

    int integerArray[5] = {10, 20, 30, 40, 50}; int *pointerToArray = integerArray;

This establishes pointerToArray as a pointer pointing to the first element of integerArray.

Accessing Array Elements with Pointers

  • Array elements can be accessed using pointers and pointer arithmetic:

    int thirdElement = *(pointerToArray + 2);

Here, pointerToArray + 2 calculates the address of the third element, and *(pointerToArray + 2) retrieves its value.

Iterating Through Arrays with Pointers

  • Pointers facilitate array traversal using loops:

    for (int i = 0; i < 5; ++i) { printf("%d ", *(pointerToArray + i)); }

This loop prints each element of integerArray by utilizing pointer arithmetic.

Pointer Arithmetic and Array Names

  • Array names, when used in expressions, behave like pointers to their first elements:

    int firstElement = *integerArray;

This assigns the value of the first element of integerArray to firstElement.

Passing Arrays to Functions using Pointers

  • Arrays can be passed to functions using pointers:

    void printArray(int *arr, int size) { for (int i = 0; i < size; ++i) { printf("%d ", *(arr + i)); } }

This function prints the elements of an array by accepting a pointer to its first element.

Understanding array pointers is fundamental for efficient array manipulation, especially when dealing with larger datasets.

If you have specific questions or if there are additional topics you'd like to explore, feel free to ask!

Last modified: 25 February 2024