C - Pointers and One-Dimensional Arrays

Pointers and one-dimensional arrays in C are closely related. In fact, in C, the name of an array is essentially a pointer to its first element. This means you can use pointers to access and manipulate the elements of an array.

Here's an example of how pointers and one-dimensional arrays work together:

#include <stdio.h>

int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr; // Pointer to the first element of the array

// Access and print elements using pointers
for (int i = 0; i < 5; i++) {
	printf("Element %d: %d\n", i, *(ptr + i));
}

return 0;
}

Output:

Element 0: 10
Element 1: 20
Element 2: 30
Element 3: 40
Element 4: 50

In this example:

  1. We declare an integer array arr with five elements.
  2. We declare a pointer ptr and initialize it with the address of the first element of the array (arr[0]).
  3. We use a for loop to access and print the elements of the array using pointer arithmetic. We add i to the pointer ptr to move to the next element in each iteration and then dereference the pointer to access the value.

Here are some key points to understand about pointers and one-dimensional arrays in C:

  1. The name of the array (arr in this case) is a pointer to its first element.
  2. Pointer arithmetic allows you to move through the elements of the array.
  3. You can access array elements using either array subscript notation (e.g., arr[i]) or pointer arithmetic (e.g., *(ptr + i)).
  4. Pointers provide flexibility when working with arrays, especially when dealing with dynamic memory allocation and passing arrays as function arguments.
  5. Be cautious when using pointer arithmetic to ensure you don't access elements outside the bounds of the array.

Understanding the relationship between pointers and one-dimensional arrays is fundamental in C programming. The name of the array is a pointer to its first element, and pointer arithmetic allows you to traverse the elements efficiently.