-1

在 Visual Studio 中,我可以清楚地看到rstr()(反转字符串)函数返回“olla\0”,但控制台显示显示不可读的字符符号。此外,由于某种原因,在调用 之后printf()reverse在调试模式下观察变量时,变量也会转换为不可读的字符值。有谁知道如何正确显示返回的字符串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;
}
4

1 回答 1

2
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.

于 2017-11-29T22:20:27.290 回答