Pointers and Arrays in C

Pointers and arrays are closely related in C. The name of an array acts as a pointer to its first element. Understanding this relationship is crucial for effective array manipulation and pointer arithmetic.

Key Topics

1. Array Name as a Pointer

The array name refers to the address of the first element.

int arr[5];
int *ptr = arr; // Equivalent to int *ptr = &arr[0];

2. Pointer Arithmetic

Pointers can be incremented or decremented to point to other elements in the array.

Example: Incrementing a Pointer

int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr;
for (int i = 0; i < 5; i++) {
    printf("%d ", *ptr);
    ptr++;
}

Output:

10 20 30 40 50 
                

3. Accessing Array Elements Using Pointers

Example: Using Pointer Notation

int arr[] = {5, 10, 15, 20};
for (int i = 0; i < 4; i++) {
    printf("Element %d: %d\n", i, *(arr + i));
}

Example: Modifying Array Elements via Pointers

int arr[3] = {1, 2, 3};
int *ptr = arr;
*(ptr + 1) = 20; // Modifies arr[1]
for (int i = 0; i < 3; i++) {
    printf("%d ", arr[i]);
}

Output:

1 20 3 
                

Best Practices

  • Use pointer arithmetic carefully; ensure pointers stay within array bounds.
  • Prefer array notation for clarity unless pointer arithmetic is necessary.
  • Initialize pointers before use to avoid undefined behavior.

Don'ts

  • Don't dereference pointers beyond the array limits.
  • Don't assume that pointer arithmetic will behave the same for different data types.
  • Don't modify array names; they are constant pointers.

Key Takeaways

  • The array name acts as a pointer to the first element of the array.
  • Pointers can be used to access and manipulate array elements efficiently.
  • Understanding the relationship between pointers and arrays enhances your ability to write more flexible code.