pointer to char related

Consider code below:

1
2
3
4
5
6
7
8
9
10
11
12
int i = 3;
int *pi = &i;

double d = 5.2;
double *pd = &d;

char c = 'j';
char *pc = &c;

cout << pi << endl;
cout << pd << endl;
cout << pc << endl;

Here clearly pc does not return an address, and I forget why. all I can remember is that pc receive a pointer to the address of character 'j', but cout will keep reading from that address untill it encouter a null-terminated character.

1: Please correct me if I am wrong and feel welcome to add any additional info about the issue.

2: How can I get the address of c?
You are correct, the << operator overload between an std::ostream (like cout) and a char* interprets the char* as being a pointer to a null-terminated c-style string.

Therefore, your program engenders undefined behavior (out-of-bounds array access) because c is not a null-terminated string.

To avoid this, cast pc to a void*.
cout << (void*)pc << endl;
Last edited on
Thank you very much @Ganado)
Topic archived. No new replies allowed.