C Pointers and Arrays
1. Array Name as a Pointer
-
In C, the name of an array is treated as a pointer to its first element.
-
That means:
-
numbers→ address of the first element (numbers[0])
2. Accessing Array Elements Using Pointers
Using pointer arithmetic
Output:
*(ptr + i)accesses the i-th element by moving the pointer.
Equivalent Using Array Index
-
numbers[i]is the same as*(numbers + i)in C.
3. Modifying Array Elements Using Pointers
Output:
4. Array of Pointers
-
You can also have an array of pointers, each pointing to a variable or string.
Output:
Useful for storing multiple strings efficiently.
5. 2D Arrays and Pointers
-
A 2D array can be accessed using pointers:
Output:
6. Key Points About Pointers and Arrays
-
Array name = pointer to first element.
-
Access elements with pointer arithmetic:
*(ptr + i)=array[i]. -
Pointers can modify array elements directly.
-
Array of pointers can store multiple strings efficiently.
-
For 2D arrays, pointer-to-array syntax:
int (*ptr)[cols].
