当字符串与数组值串联时,Cout打印垃圾

发布于 2025-01-25 10:14:46 字数 239 浏览 2 评论 0原文

这是我非常基本的C ++代码:

#include <iostream>

char values[] = {'y'};

int main() {
    std::cout << "x" + values[0];
}

我的预期输出仅为xy,但我只是得到随机的文本/符号

Here is my very basic C++ code:

#include <iostream>

char values[] = {'y'};

int main() {
    std::cout << "x" + values[0];
}

My expected output would just be xy, but instead I am just getting random text/symbols

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

遮云壑 2025-02-01 10:14:46

也许您打算要做:

std::cout << "x" << values[0];

否则,您正在使用“ x”(它衰减到指向const数组的第一个元素的指针中,该元素保存字符{'x'x''\ 0'}在内存中),然后添加'y'(将数字值121转换为int)那个指针。

将整数添加到指针上更改指向的内容。您正在阅读内存的内存,超出了'x'字符,因此您将要读取随机字节或引起访问违规行为。

Perhaps you meant to do:

std::cout << "x" << values[0];

Otherwise, you are taking "x" (which decays into a pointer to the 1st element of a const array that holds the characters {'x', '\0'} in memory), and adding 'y' (which has the numeric value 121 when converted to an int) to that pointer.

Adding an integer to a pointer changes what it points to. You are reading memory that is 121 bytes beyond the 'x' character in memory, so you are going to be reading random bytes, or causing an Access Violation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文