Wednesday 13 February 2013

Pointer Arithmetic of incrementing and decrementing



Arithmetic operations of incrementing and decrementing can be performed on pointers. In fact, pointer arithmetic is one of the reasons why it is essential to declare a pointer as pointing to a certain datatype so that when the pointer is incremented or decremented, it moves by the appropriate number of bytes. Thus, a simple satement like

ptr++;

does not neccessarily mean that ptr now points to the next memory location. What memory location it will point to depend upon the datatype to which the pointer points.

Consider the following example:

#include<stdio.h>

char movie[] = "Jurassic Park";

main()
{
char *ptr;
ptr=movie;
printf("%s", movie);

printf("%s", ptr);

ptr++;

printf("%s", movie);

printf("%s", ptr);

ptr++;

printf("%s", movie);

printf("%s", ptr);

}

0 comments:

Post a Comment

Powered by Blogger.