I have a char* and I’m assigning another char* to it. I want to know what all is going to happen through that instruction?
For example:
char* foo; // suppose it is initialized and defined
char* bar = foo // I am defining bar
What all would happen(to foo and bar) after calling the assignment operation wrt values, memory etc.
I am new to C, maybe very trivial question for some of you.
>Solution :
Lets say we have two pointers initialized to point to different strings:
const char *foo = "abcd";
const char *bar = "efgh";
If we "draw" how they would look in memory, it would be something like this:
+-----+ +--------+ | foo | ---> | "abcd" | +-----+ +--------+ +-----+ +--------+ | bar | ---> | "efgh" | +-----+ +--------+
Then we assign to bar:
bar = foo;
Then it would look something like this instead:
+-----+ +--------+
| foo | -+-> | "abcd" |
+-----+ | +--------+
|
+-----+ | +--------+
| bar | -/ | "efgh" |
+-----+ +--------+
Now both foo and bar are pointing to the same location.
In shorter form, that’s what a definition with initialization like:
const char *bar = foo;
will do.