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

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

Leave a Reply