- 2068 Chaitra · 1+1 marks
Accessing array elements using pointer
Short answer
Pointers hold addresses, enabling call by reference, dynamic memory, and efficient array handling. To access array elements, set a pointer to the array name (address of first element); then *(p+i) gives a[i], and pointer arithmetic like p++ traverses the array.
Explain how pointers can be used in C. How can you access array elements using pointer.
Use of pointers in C
A pointer is a variable holding the address of another variable. It is used for call by reference, dynamic memory allocation (malloc), efficient array and string handling, and building data structures such as linked lists and trees.
Accessing array elements with a pointer
The array name is the address of its first element, so a pointer can be set to it: int *p = a;. Then:
*pisa[0],*(p + 1)isa[1], and in general*(p + i)isa[i].- The pointer can be moved with
p++to visit the next element.
#include <stdio.h>
int main(void)
{
int a[5] = {5, 10, 15, 20, 25}, *p = a, sum = 0;
for (int i = 0; i < 5; i++)
printf("a[%d] = %d\n", i, *(p + i)); /* value using pointer */
for (p = a; p < a + 5; p++) /* moving the pointer */
sum += *p;
printf("Sum = %d\n", sum);
return 0;
}
Output:
a[0] = 5
a[1] = 10
a[2] = 15
a[3] = 20
a[4] = 25
Sum = 75
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Pointers in pass by reference; 2D array · Computer Programming, chapter 9
- Structure vs array; accessing members · Computer Programming, chapter 8
- Array of pointers · Computer Programming, chapter 9
- Relation between array and pointer · Computer Programming, chapter 9 · asked 5×
- Reverse array and display via pointer · Computer Programming, chapter 9
- Second largest element using pointer · Computer Programming, chapter 9
- Yagi parasitic elements and LPDA comparison · Propagation and Antenna, chapter 3 · asked 3×
- Access specifiers in inheritance · Object Oriented Programming, chapter 6
- Strowger subscriber access design approaches · Telecommunications, chapter 1
- Access overridden members from derived class · Object Oriented Programming, chapter 6 · asked 2×