Home >Backend Development >C++ >Explain the concepts of pointers and arrays in C language

Explain the concepts of pointers and arrays in C language

WBOY
WBOYforward
2023-09-12 14:49:01802browse

Pointers and Arrays

The compiler allocates contiguous memory locations for all elements of an array.

The base address is the position of the first element in the array.

For example, int a [5] = {10, 20,30,40,50};

The storage of these five elements is as follows −

Explain the concepts of pointers and arrays in C language

If &p' is declared as an integer pointer, you can point to the array &a' by the following assignment −

p=a
or
p=&a[0];

Move from one element to another by using p to access the value of each &a. When a pointer is incremented, its value increases by the size of the data type pointed to. This length is called the "scale factor".

The relationship between pointer p and variable a is as follows −

P   = &a[0] = 1000
P+1 = &a[1] = 1004
P+2 = &a[2] = 1008
P+3 = &a[3] = 1012
P+4 = &a[4] = 1016

The address of an element is calculated using its index and the scaling factor of the data type.

Example

The address of a[3]=base address (scaling factor int of 3*a)

      =1000 (3*4)

=1000 12

=1012

*(p+3) gives the value of a[3]
a[i] = *(p+i)

Program

#include<stdio.h>
main (){
   int a[5];
   int *p,i;
   clrscr ();
   printf (&rdquo;Enter 5 lements&rdquo;);
   for (i=0; i<5; i++)
      scanf (&ldquo;%d&rdquo;, &a[i]);
   p = &a[0];
   printf (&ldquo;Elements of the array are&rdquo;);
   for (i=0; i<5; i++)
      printf(&ldquo;%d&rdquo;, *(p+i));
   getch();
}

Output

Enter 5 elements : 10 20 30 40 50
Elements of the array are : 10 20 30 40 50

The above is the detailed content of Explain the concepts of pointers and arrays in C language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete

Related articles

See more