-1
int main()
{ 
     char s[]="stack";
     s="overflow";
}

This is not allowed.Its gives an error.But below code works fine.

int main()
{
      char s[]="stack";
      strcpy(s,"overflow");
}

Why this happens?

karthikr
  • 97,368
  • 26
  • 197
  • 188

1 Answers1

-1

The variable s represents a pointer to the string. More specifically, it refers to the memory address of the first letter in your string "stack". Due to this reason, the operation s="overflow" makes no sense. How can you set the value of s (a pointer) to a string?

Keep in mind that C is a very low-level language, so you have to be wary of things that might seem intuitive to you not behaving the way you expect them to.

Lanaru
  • 9,421
  • 7
  • 38
  • 64
  • It doesn't decay into a pointer. It's a character array and you can't change the base address of an array once allocated. – Uchia Itachi Aug 23 '13 at 18:50
  • You can't change it, but you can treat it like a pointer in some cases (such as for pointer arithmetic: `s + 1` refers to the second character in the array). – Lanaru Aug 23 '13 at 18:56
  • Yes, true indeed. But your `How can you set the value of s (a pointer) to a string?` statement is misleading. – Uchia Itachi Aug 23 '13 at 19:00