当字符串与数组值串联时,Cout打印垃圾
这是我非常基本的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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许您打算要做:
否则,您正在使用
“ x”
(它衰减到指向const数组的第一个元素的指针中,该元素保存字符{'x'x'
,'\ 0'
}在内存中),然后添加'y'
(将数字值121转换为int
)那个指针。将整数添加到指针上更改指向的内容。您正在阅读内存的内存,超出了
'x'
字符,因此您将要读取随机字节或引起访问违规行为。Perhaps you meant to do:
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 anint
) 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.