Printing each character of char array instead of each partial one

Recently I found an interesting question in my exam: what would be printed by the following code. I wondered why this code didn't print sequentially each character of the char array (i.e "dcba") but each partial one (i.e "dcdbcdabcd"), in the reverse order.

By the way, I also want to know which topic is related to this problem.

Thank you!

#include <iostream>
#include <string.h>

int main()
    char mess[] = "abcd";
    char* ptr;
    ptr = mess + strlen(mess);
    while (ptr > mess)
        printf("%s", --ptr);
    return 0;

2 answers

  • answered 2021-09-25 05:31 Allan Wind

    char mess[] = "abcd"; means mess aka &mess[0] is the address of the string {'a', 'b', 'c', 'd', \0 }. ptr = mess + strlen(mess); means ptr initially points to the \0 of mess. In the loop ptr is decremented, and the subsequent printf() will print from where ptr points to till it sees \0 (i.e. tail of mess):

    // initial:
    ^----- mess aka &mess[0]
         ^ ptr = mess + strlen(mess) = mess + 4

  • answered 2021-09-25 05:32 The Long Nguyen

    It's because your formatter in printf printing a string each time, not a character. So it print the string start at ptr to the end of mess.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum