0

Using pointers string can be initialized to other characters but when once string has been defined it cannot be initialized to other characters.What is the reason behind it??

int main()
{
char str1[]="hello";
char *p="hello";
str1="bye";/*error*/
p="bye";/*works*/
}
amadeus
  • 69
  • 4
  • Nick: In this case, the * (in "char *p") means that p is a pointer variable. That is, the variable p doesn't contain a character, but the address to a place in memory where there is a character. – Thomas Padron-McCarthy Jul 08 '12 at 08:33
  • pl. also see some useful links http://c-faq.com/decl/strlitinit.html – Tanmoy Bandyopadhyay Jul 08 '12 at 08:37
  • A more pertinent duplicate would discuss the use of `strcpy()` et al for assigning to strings. The proposed duplicate does not do that. Other questions might be more appropriate. A casual search found: [Why is `strcpy()` necessary?](http://stackoverflow.com/questions/6901090/) and [Why does a char array need `strcpy` and `char *` doesn't](http://stackoverflow.com/questions/11508233/). – Jonathan Leffler Apr 01 '14 at 05:22

3 Answers3

1

You've defined str1 as an array, and arrays aren't assignable.

You can, however, copy other data into the array, for example:

char str1[] = "hello";

strcpy(str1, "bye");
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
0

To change the characters in an array such as what you are doing you have to use a function such as strcpy or do it index by index.

str1[0] = 'p';

will print out pello

What you are trying to do is not supported by the C language.

sean
  • 3,955
  • 21
  • 28
0

Arrays are arrays and pointers are pointers. Defining arrays gives the pointer to the allocated array, that is a constant pointer to the location where the array space hass been reserved. That is a concrete address in the lifo stack. So, str1 is a constant pointer value and you cannot change it. You cannot set the value of the address of a different constant string.

Defining pointers, as char*p, gives you a variable value of an address. And so, you can change de value of the variable p.

Gabriel
  • 3,319
  • 1
  • 16
  • 21