1

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?

1 Answer 1

5

char *name[]={a,b};//each item inside name is not string literal rite?? - not quite, each element is a pointer to a char.

So name is 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 strncpy in 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 a char* for *name="bye")

Before *name="bye":

State before

After *name="bye":

State after

Sign up to request clarification or add additional context in comments.

6 Comments

When i debugged i found what you are saying is happening. But *name has the address of a[] rite? Any modification to *name has to be reflected in a[] rite?. Nope i didn't get any warnings.
No. *name is a pointer still, that points to a. *name changes what the pointer points to.
So now that *name has changed to point to something else, looking for b and expecting it to be "hello" isn't really valid, right?
b isn't changed at all. It's still valid, it' still pointed to by the 2nd element of name.
Thanks for your explanation. Can you explain why this doesn't work **name="hi"
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.