Skip to main content

Command Palette

Search for a command to run...

Array indexing and their equivalent pointer expressions

Updated
•1 min read•View as Markdown
Array indexing and their equivalent pointer expressions

In C, when you use array indexing, such as a[i], it's equivalent to dereferencing a pointer offset a by i, which is represented as *(a + i).

This is because arrays in C are essentially contiguous blocks of memory, and indexing into an array can be thought of as accessing the memory location at the base address of the array plus the offset provided by the index.

So basically all of the following four programs produce the same output.

Program 1:

#include <stdio.h>
 int main()
 {
 int a[]={10, 20, 30, 40, 50};
 int i;
 for(i=0;i<5;++i)
 printf("\n%d", a[i]);
 return 0;
 }

Program 2:

#include <stdio.h>
 int main()
 {
 int a[]={10, 20, 30, 40, 50};
 int i;
 for(i=0;i<5;++i)
 printf("\n%d", *(a+i));
 return 0;
 }

Program 3:

#include <stdio.h>
 int main()
 {
 int a[]={10, 20, 30, 40, 50};
 int i;
 for(i=0;i<5;++i)
 printf("\n%d", *(a+i));
 return 0;
 }

Program 4:

#include <stdio.h>
 int main()
 {
 int a[]={10, 20, 30, 40, 50};
 int i;
 for(i=0;i<5;++i)
 printf("\n%d",i[a]);
 return 0;
 }

Output:

12 views

More from this blog

P

Programming Tutorials

89 posts