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

Dereferencing a char pointer when its equated to another char pointer

Here is my code

    char *sptr = "abc", *tptr;

    *tptr = *sptr;

    printf("ch = %c\n", *tptr);

Now, when we declare a pointer, no memory is allocated to store char variable. So, this code does run and 'a' is printed on the console. I know that "abc" is a string literal and its a read only memory. But when I execute *tptr = *sptr , where is *tptr is stored ?

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

>Solution :

The assignment *tptr = *sptr; invokes undefined behavior, since you’re storing through an undefined pointer. It’s a severe bug. Instead, you can do tptr = sptr;, which gives tptr the same value as sptr.

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