Pointer to array

  • March 27, 2022
  • C
Matrix multiplication

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

Leave a Reply

Your email address will not be published. Required fields are marked *