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

What is object oriented design patterns

A design pattern is a reusable solution to a commonly occurring problem in software design. They…

4 months ago

Factory Method Design Pattern in OODP

Factory Method is a creational design pattern that deals with the object creation. It separates…

4 months ago

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

10 months ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

10 months ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

10 months ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

11 months ago