Search code examples
cstringprintfconst-char

Why can't my call to printf() display the right characters in console?


In visual studio, I can clearly see that the rstr() (to reverse string) function returns "olla\0", but the console display shows unreadable character symbols. Also, for some reason, after the call to printf(), the variable reverse transforms into unreadable character values too while watching variables in debug mode. Does anyone know how to correctly display the string returned by rstr()?

#include "stdio.h"

const char* rstr(const char* message) {

    const int msg_size = sizeof(message) / sizeof(message[0]);
    char r[msg_size + 1];

    for (int i = 0; i < msg_size; ++i) {
        r[i] = message[msg_size - i - 1];
        if (i == (msg_size - 1))
            r[msg_size] = '\0';
    }

    return r;
}

int main() 
{
    const char* reversed = rstr("allo");
    printf("Reversed string is: %s\n", reversed);

    getchar();
    return 0;
}

Solution

  • const int msg_size = sizeof(message) / sizeof(message[0]);
    

    is all wrong here.

    message is a char*, so sizeof(message) will be the size of a pointer to char.

    And since message[0] is a char, sizeof(message[0]) is one by definition. So your msg_size will be the size of a pointer to char.

    You need to pass the length of the String into your rstr() function.