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.
CodePudding user response:
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.
CodePudding user response:
In, char* bar = foo
, the = foo
is technically an initialization, not an assignment. Initialization follows many of the rules of assignment.
Since foo
is a pointer to char
, and you say it has been initialized, it has a “value” that is a reference to some char
object (or a null pointer). We often think of these values as addresses in computer memory. The initialization or assignment merely gives bar
the same value.
Values are represented with bytes. So, to record the value of foo
, there are some bytes in the memory reserved for foo
. To set bar
to the same value, all the compiler has to do is copy the bytes from the memory of foo
to the memory of bar
.