Thursday, November 10, 2011

pointers and increments

Today's 2 questions are based on pointers. Pretty easy ones for you C punters out there.


1) What is the output of the following?
This is based on the question here

#include <stdio.h>

main()
{
   char *ptr =" DARN C !";
   *ptr++;
   printf("%s\n",ptr);
   ptr++;
   printf("%s\n",ptr);

}


Answer:
DARN C !
ARN C !


2) On similar lines, what is the output of this one?

#include <stdio.h>

main()
{
   int array[] = {1, 10, 100, 1000, 10000};
   int *parray = array;

   *parray++;
   printf("%d\n", *parray);

   parray++;
   printf("%d\n", *parray);

   (*parray)++;
   printf("%d\n", *parray);
}



Answer:
10
100
101


If p is a pointer, what is the difference between *p++, p++ and (*p)++ ?

*p++ increments the pointer and dereferences it
p++ increments the pointer
(*p)++ increments the value pointed to by the p




No comments:

Post a Comment