Array using pointers

Home / C Programming / Array using pointers

Array using pointers


In C, arrays and pointers are closely related. In fact, when you work with arrays, you are often using pointers to access and manipulate the elements of the array. Arrays decay into pointers when passed as arguments to functions or when used in most expressions. Here's how you can use pointers to work with arrays in C:

Accessing array elements using pointers:

You can use a pointer to traverse the elements of an array. When an array is used with a pointer, it points to the first element of the array.


// Output:

// Element 0: 1

// Element 1: 2

// Element 2: 3

// Element 3: 4

// Element 4: 5

Passing arrays to functions using pointers:

Arrays are commonly passed to functions using pointers. When you pass an array to a function, you are actually passing the address of the first element of the array.


// Output: 10 20 30 40 50

Dynamic allocation of arrays using pointers:

You can dynamically allocate memory for arrays using pointers and pointer arithmetic.


Remember that arrays, when used with pointers, are zero-indexed. Therefore, the first element of the array corresponds to the pointer without any additional offset (i.e., arr[0] is equivalent to *arr). Pointer arithmetic is automatically scaled by the size of the data type, so you don't need to explicitly multiply by the size when accessing elements using pointers.