0

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 thisenter image description here:

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.

  • Possible duplicate of [cout << with char\* argument prints string, not pointer value](https://stackoverflow.com/questions/17813423/cout-with-char-argument-prints-string-not-pointer-value) - `< – kabanus Jan 03 '18 at 11:11
  • Yep I think it must be something like that, just found the answer in an old thread I linked below thx. – SpelingError Jan 03 '18 at 11:19

1 Answers1

0

Never mind. I guess the solution is this:

std::cout << *t2 << std::endl;
std::cout << (void*)t2 << std::endl;
std::cout << std::endl;

Also found: Why is address of char data not displayed?