-3
char *str1;
str1 = "Hello";

In the above code, does str1 = "Hello"; indicate string copy? what are the reasons?

chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • 2
    No. It indicates pointer assignment. – machine_1 Mar 24 '18 at 10:05
  • 2
    [so] is not the place to learn language basic. You should use language tutorial/reference sites instead. – user202729 Mar 24 '18 at 10:06
  • 1
    The constant string literal `"Hello"` is a read-only array of six characters. The assignment makes `str1` point to the first element of that array. So in a way it *is* copying, but not what you probably think it's copying. What's copied is the address of the first element. – Some programmer dude Mar 24 '18 at 10:07
  • Not a string copy. In memory "Hello" is stored and corresponding memory pointer is assigned to str1. – Austin Mar 24 '18 at 10:07

1 Answers1

0

Actually, C language itself is not fully aware of strings. It only handles characters and pointers to them. What makes a C string is a convention by which an array of characters (an array is just a pointer to an allocated blob of memory) terminated by a null character '\0' can be handled as a string.

The only place where C is aware of strings is literal constants in code, like "Hello" in your example, which allocate memory containing those characters and followed by '\0'.

char * does not declare a string variable. It declares a pointer to a character.

mouviciel
  • 66,855
  • 13
  • 106
  • 140