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
Release: 2023-09-12 14:49:01
forward
801 people have browsed it

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];
Copy after login

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
Copy after login

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)
Copy after login

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();
}
Copy after login

Output

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

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template