This seems like it should be easy but i’ve spent way too much time on it. Hopefully someone can help.
char *labels[] = { "apple", "orange" }; // each items inside label is string literal. We can't change them-
Look at the below
char a[]="hi";
char b[]="hello";
char *name[]={a,b};//each item inside name is not string literal rite??
*name="bye";
puts(a);
I thought output will be bye since i changed the content of a[] using *name="bye"
But the output is still hi. why?
char *name[]={a,b};//each item inside name is not string literal rite??– not quite, each element is a pointer to achar.So
nameis an array of pointers.*name="bye"changes what the first of those pointers change to. It doesn’t change the memory that the old pointer pointed to.If you wanted to do that you would use
strncpyin general, but note that here you don’t have a large enough array to do that.(I would also have expected your compiler to give you a warning about assigning a
const char *to achar*for*name="bye")Before
*name="bye":After
*name="bye":