Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

printing with pointers and strings (C)

can someone explain why this prints out : "d ce" I think i understood why it prints out "d" but i don't understand the "ce"

#include <stdio.h>

int main(void){
    char s1[]="abcd",*cp;

    cp=s1+2;
    printf("%c %s
",(*(++cp))++,s1+2);

    return 0;
}

question from:https://stackoverflow.com/questions/65842838/printing-with-pointers-and-strings-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Hope the inline comments makes it clear.

#include <stdio.h>

int main()
{
    char s1[]="abcd",s2[]="cdef",s3[5],*cp;

    printf("s1 = %p
", (void*)s1); // prints start address of s1
    
    cp = s1+2; // cp points to 2 chars advanced of s1 i.e 'c'
    
    printf("cp = %p
", (void*)cp); // prints address at 'c'
    //first increment cp to point to next location, which now points at 'd' from 'c'
    //the outer ++ increments 'd' to 'e' post-fix, so first prints 'd'
    printf("(*(++cp))++ = %c
", (*(++cp))++); 
                                               
    printf("s1 = %s
", s1); // you will see "abce"
    printf("s1+2 = %s
", s1+2); // 2 chars advanced of s1, i.e "ce"
    
    //printf("%c %s
",(*(++cp))++,s1+2);

    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...