Awesome q2a theme
+1 vote
32 views

Can anyone please explanataion of output of below 2 programs

#include<stdio.h>

int main()

{

  char arr[] = "geeksforgeeks";

  char *p = arr;

  ++*p;

  printf(" %c", *p);

  getchar();

  return 0;

}

and

 

// Program 2

#include<stdio.h>

int main()

{

  char arr[] = "geeksforgeeks";

  char *p = arr;

  *p++;

  printf(" %c", *p);

  getchar();

  return 0;

}

in Programming by (9 points) | 32 views

1 Answer

+3 votes

Initially, when you do char *p=arr; it means p=&arr[0], i.e. is pointer to first character in the char array arr.

Program 1:

When you do ++*p; 

Unary ++ and Pointer (*) operators have same precedence and both are right to left associative, so this statement is equivalent to:

++(*p);

 

Which is same as:

++arr[0];  

 

Hence, arr[0] will now become ’g’+1 i.e. ’h’

Then you print *p which is same as arr[0], Hence the output will be h.

 

Program 2:

In the statement *p++; postfix operator ++ has higher precedence (moreover, postfix operators have highest precedence among all operators), so this statement will be equivalent to:

*(p++);                     

//this statement evaluates to arr[0], if you would have assigned *p++, to any character, then it would have become arr[0], i.e. ‘g’

 

For the given program, the only useful operation that will affect the output is p++, because you are printing the value of *p after this operation. So, new value of p will be p+1, since  p was the address of arr[0], p+1 will be the address of arr[1], hence, now points to arr[1], hence, when you print *p, the output will be arr[1], i.e. character will be printed.

by (855 points)
edited by
0
Pointers are well explained, thanks brother
Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
Welcome to GATE CSE Doubts, where you can ask questions and receive answers from other members of the community.
8,446 questions
2,720 answers
13,274 comments
95,468 users