Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
An Uncommon representation of array elements in C/C++
In C, array elements can be accessed in several ways. While the most common method is using the subscript operator (array[i]), we can also use pointer arithmetic to access elements in an uncommon but valid representation.
Syntax
*(array + index) // Equivalent to array[index]
Example: Pointer Arithmetic Array Access
This example demonstrates how to access array elements using pointer arithmetic instead of the traditional subscript notation −
#include <stdio.h>
int main() {
int array[5] = {7, 7, 7, 6, 6};
printf("Array elements using pointer arithmetic: ");
for (int i = 0; i < 5; i++) {
printf("%d ", *(array + i));
}
printf("\n");
return 0;
}
Array elements using pointer arithmetic: 7 7 7 6 6
Comparison of Access Methods
| Method | Syntax | Description |
|---|---|---|
| Subscript Notation | array[i] |
Most common and readable |
| Pointer Arithmetic | *(array + i) |
Shows underlying pointer operation |
| Array as Pointer | *(i + array) |
Commutative property (unusual but valid) |
How It Works
When you declare an array, the array name acts as a pointer to the first element. The expression *(array + i) adds i to the base address and dereferences it to get the value at that location.
Conclusion
While *(array + i) is a valid way to access array elements in C, the traditional array[i] notation is preferred for better readability and maintainability. Understanding pointer arithmetic helps grasp how arrays work internally.
