Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

cout printing garbage when string is concatenated with array value

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Perhaps you meant to do:

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

Otherwise, you are taking "x", which is a pointer to the characters ‘x\0’ in memory, and adding ‘y’ to it, which has the value 121 when converted to an int.

Adding 121 to a pointer changes what it points to, so you are reading memory 121 bytes beyond your "x" string in memory, which is going to be random bytes, or cause an access violation.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading