Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What does char* assignment do?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading