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

I dont understand why the final output is "eU2"

Why is the last output "eU2"?

#include<stdio.h>
#include<string.h>

void main()
{
    char str1[] = "See the stone set in your eyes";
    char str2[] = "U2";
    char* ptr;
    ptr = &str1[3];//the stone...
    printf("%d\n", str1 - ptr); // -3
    ptr[-1] = 0;// del s
    ptr = (++ptr)+1;  
    printf("%s\n", ptr); // he stone set in your eyes
    strcpy(ptr, str1+1); // ee the stone set in your eyes
    strcat(ptr-2, str2); 
    printf("%s\n", ptr);
}

I wrote notes next to lines I understood

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 :

#include<stdio.h>
#include<string.h>

int main(void)
{
    char str1[] = "See the stone set in your eyes";
    char str2[] = "U2";
    char* ptr;
    ptr = &str1[3];// points at the space before "the stone..." 
    printf("%ld\n", str1 - ptr); // -3
    ptr[-1] = 0; // replaces the second e of see with 0 in str1
    ptr = (++ptr)+1; // points to the h of "the stone..." 
    printf("%s\n", ptr); // he stone set in your eyes
    strcpy(ptr, str1+1); // ptr points to "e\0 the stone set in your eyes"
    strcat(ptr-2, str2); // concatenates the string "e\0" with "U2\0"
    printf("%s\n", ptr); // prints eU2
}
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