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
CodePudding user response:
Based on Steve Summit's comments, I replaced ptr = ( ptr) 1
, which leads to undefined behavior, with two repetitions of ptr
.
#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 ; // 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
}