I have this code that produces an unexpected result for a char pointer:
#include <iostream>
#include <stdlib.h>
#include <string>
void main(int argv, char* argc[]) {
char* test1 = new char[7];
test1[0] = 'H';
test1[1] = 'a';
test1[2] = 'l';
test1[3] = 'e';
test1[4] = 't';
test1[5] = 'y';
test1[6] = 'a';
char* t2 = &test1[3];
std::cout << *t2 << std::endl;
std::cout << t2 << std::endl;
std::cout << std::endl;
int v[] = { 1,2,3,4 };
int* v2 = &v[0];
std::cout << *v2 << std::endl;
std::cout << v2 << std::endl;
std::cout << std::endl;
float f[] = { 0.2, 0.4, 0.6 };
float* f2 = &f[1];
std::cout << *f2 << std::endl;
std::cout << f2 << std::endl;
std::cout << std::endl;
std::string str = "A_string";
std::string *str2 = &str;
std::cout << *str2 << std::endl;
std::cout << str2 << std::endl;
std::cout << std::endl;
std::cin.ignore();
}
The output for this is variable but usually something like this:
What's going on? For the int, float, and string, printing the address prints the pointer address and printing the pointer prints the correct value. However, for the char array, while printing the pointer also prints the correct value, printing the address prints the last 4 elements of the array and a bunch of crap that varies per run.
Is there something about char that causes this or do I just have a funky setup? I've tried initializing the char array with brackets but it's the same result.