Categories: C

Pointer to array

An array name is a constant pointer to the array’s first element. As a result, in the declaration

double marks[50];

marks is a pointer to &marks[0], which is the address of the array marks’s first element. As a result, the following program fragment assigns p as the address of the element of the first marks.

double *p;
double marks[10];

p = marks;

After storing the first element’s address in ‘p,’ you can access the array elements with *p, *(p+1), *(p+2), and so on. The example below demonstrates all the concepts discussed above.

#include <stdio.h>

int main () {

   /* an array with 5 elements */   double marks[5] = {100.0, 29.0, 38.4, 87.0, 75.0};
   double *p;
   int i;

   p = marks;
 
   /* output each array element's value */   printf( "Array values using pointer\n");
 
   for ( i = 0; i < 5; i++ ) {
      printf("*(p + %d) : %f\n",  i, *(p + i) );
   }

   printf( "Array values using marks as address\n");
 
   for ( i = 0; i < 5; i++ ) {
      printf("*(marks + %d) : %f\n",  i, *(marks + i) );
   }
 
   return 0;
}
Output:
Array values using pointer
*(p + 0) : 100.000000
*(p + 1) : 29.000000
*(p + 2) : 38.400000
*(p + 3) : 87.000000
*(p + 4) : 75.000000
Array values using marks as address
*(marks + 0) : 100.000000
*(marks + 1) : 29.000000
*(marks + 2) : 38.400000
*(marks + 3) : 87.000000
*(marks + 4) : 75.000000

In the preceding example, p is a pointer to double, which means it can store the address of a double-type variable. As shown in the preceding example, once we have the address in p, *p will return the value available at the address stored in p.

Note: also read about the Pointer in C

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago

Binary Search Tree (BST)

A Binary Search Tree (BST) is a type of binary tree that satisfies the following…

1 year ago