Pointer to 1D Array in C
Notes:
Pointer to One Dimensional ( 1D ) Array in C Programming Language:
- Pointer is a variable which holds the address of another memory location
- Array is a contiguous collection of homogeneous data elements
Declaring and initializing a 1D array:
datatype arrayName[size] = {list of values separated by comma};
Ex:
int numbers[5] = {1, 2, 3, 4, 5};
Accessing array elements using arrayName and its index:
There are 2 different ways in which we can access each element in an array using arrayName and its index
1. Subscript notation: arrayName[index] Ex: numbers[0]
2. Pointer notation: *(arrayName + index) Ex: *(numbers + 0)
Declaring and initializing a pointer to a 1D array:
datatype *pointerName = &arrayName[index];
Ex:
int *iptr = &numbers[0];
Accessing array elements using pointerName and element index:
There are 2 different ways in which we can access each element in an array using pointerName and its index
1. Subscript notation: pointerName[index] Ex: iptr[0]
2. Pointer notation: *(pointerName + index) Ex: *(iptr + 0)
Example Code:
#include <stdio.h>
int main()
{
int numbers[5] = {1,2,3,4,5};
int *iptr = &numbers[0];
printf("%d\n", numbers[0]); // 1
printf("%d\n", numbers[1]); // 2
printf("%d\n", numbers[2]); // 3
printf("%d\n", numbers[3]); // 4
printf("%d\n", numbers[4]); // 5
printf("\n");
printf("%d\n", *(numbers + 0)); // 1
printf("%d\n", *(numbers + 1)); // 2
printf("%d\n", *(numbers + 2)); // 3
printf("%d\n", *(numbers + 3)); // 4
printf("%d\n", *(numbers + 4)); // 5
printf("\n\n");
printf("%d\n",iptr[0]); // 1
printf("%d\n",iptr[1]); // 2
printf("%d\n",iptr[2]); // 3
printf("%d\n",iptr[3]); // 4
printf("%d\n",iptr[4]); // 5
printf("\n");
printf("%d\n", *(iptr + 0)); //1
printf("%d\n", *(iptr + 1)); //2
printf("%d\n", *(iptr + 2)); //3
printf("%d\n", *(iptr + 3)); //4
printf("%d\n", *(iptr + 4)); //5
return 0;
}