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
CodePudding user response:
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.