1

I am wondering why the expected output for the below program is not "hai"

#include<stdio.h>
#include<conio.h>

void first(char*);
void first(char *s)
{
  printf("%u",s);
  s="hai";
}

int main()
{
 clrscr();
  char *t ="welcome";
  printf("%u",t);
   first(t);

 printf("%s",t);
  getch();
  return 0;
}

The output am getting is Welcome instead of Hai.

It would be more helpful, if somebody can explain in detail ?

  • 1
    `s="hai";` changes the local pointer, not the caller's pointer – UnholySheep Mar 23 '18 at 14:43
  • Why would it be "hai"? You only modify the local copy of a variable, after all. Consider learning from a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) instead of coding randomly. SO is not a tutorial service. – Algirdas Preidžius Mar 23 '18 at 14:44
  • I don't understand can you explain bit more ? – Prasath Shanmugakani Mar 23 '18 at 14:44
  • Short explanation: there is nothing special about pointers. – molbdnilo Mar 23 '18 at 14:46
  • Another dupe: https://stackoverflow.com/questions/27483368/basic-c-pointer-and-pass-by-reference-confusion – melpomene Mar 23 '18 at 14:53
  • @AlgirdasPreidžius that's pretty cold. – noelicus Mar 23 '18 at 14:53
  • @noelicus Please elaborate: why do you think so, or why should I feel warm and fuzzy, for all questions, where asker didn't bother at performing any research? – Algirdas Preidžius Mar 23 '18 at 14:56
  • Please note that the format specifier `%u` is used to convert an unsigned integer into its decimal representation, not to print character arrays. Is it a typo? How many warnings/errors did you get from your compiler? – Bob__ Mar 23 '18 at 14:56

1 Answers1

2

Everything in C is passed by value. Including pointers. So you have passed a memory address (pointer) into the function and then re-assigned it to point at a different bit of memory: to point at your "hai" string. The original pointer t is still pointing happily to your original string "welcome". When you passed t in you passed the memory address that t points to by value: that value was copied to the argument/variable s.

noelicus
  • 14,468
  • 3
  • 92
  • 111