Home > Software engineering >  Printing each character of char array instead of each partial one [duplicate]
Printing each character of char array instead of each partial one [duplicate]

Time:09-25

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;
}

CodePudding user response:

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.

CodePudding user response:

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:
abcd\0
^----- mess aka &mess[0]
     ^ ptr = mess   strlen(mess) = mess   4
  • Related