luek baja
luek baja

Reputation: 1668

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

Upvotes: 0

Views: 448

Answers (1)

Geoduck
Geoduck

Reputation: 8999

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.

Upvotes: 4

Related Questions