3,229 views
1 votes
1 votes

#include <stdio.h>

int fun(char *str1)
{
  char *str2 = str1;
  while(*++str1);
  return (str1-str2);
}

int main()
{
  char *str = "GeeksQuiz";
  char *str1 = str;
  printf("%d", fun(str));
  return 0;
}
 

str1 and str2 pointing to the same string , str1 is incrementing while str2 is still pointing to the first element, so the difference (str1 - str2) should be 51, but it shows 9, please help me to understand. 

1 Answer

4 votes
4 votes
YES! answer 9 is correct.

lets try to understand program from the beginning(i mean from main() method),

 

int fun(char *str1)  //now fun method str1 pointing to address 100
{
  char *str2 = str1;  //str2 pointing to address 100
  while(*++str1);   //as look carefully after while there is semicolon(;) which means until str1 have value other than NULL(\0) it will                              // increase so str1 is pointing to address 100 after it increment point to 101...102...103....so on 109(\0)

                          //"G->100 e->101 e->102 k->103 s->104 Q->105 u->106 i->107 z->108" [\0->109]for termination of while loop
  return (str1-str2); //as we know that difference of pointer always return no of element between the pointer address which return                                 // 109-100=9
}

int main()
{
  char *str = "GeeksQuiz";  //let beginning memory address of  "GeeksQuiz" is 100 so 100 stored in str
  char *str1 = str;  //now 100 is also storing in str1
  printf("%d", fun(str));
  return

No related questions found