Skip to main content

Command Palette

Search for a command to run...

Some more pointer arithmetic with Arrays

Updated
1 min readView as Markdown

Program 1:

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

Output:

Changing the direction of the loop:

Program 2:

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

Output:

Using array subscripting with pointer p

We have seen before that a[i] = *(a+i) = *(i+a) = i[a]

Thus *(p-i) = *(p+(-i))= p[-i]

Program 3:

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

Output:

Program 4:

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

Output:

However this doesn't work:

Program 5:

int main(void)
{
 int a[] = {10, 20, 30, 40, 50};
 int i, *p;
 p=a+4;
 for(i=0;i<=4;i++) printf("%d\n", -i[p]);
 return 0;
}

It gives logical runtime errors / undefined behavior / prints garbage values.

20 views

More from this blog

P

Programming Tutorials

89 posts