Here is the code:
#include<iostream>
struct element{
char *ch;
int j;
element* next;
};
int main(){
char x='a';
element*e = new element;
e->ch= &x;
std::cout<<e->ch; // cout can print char* , in this case I think it's printing 4 bytes dereferenced
}
am I seeing some undefined behavior? 0_o. Can anyone help me what’s going on?
You have to dereference the pointer to print the single char:
std::cout << *e->ch << std::endlOtherwise you are invoking the
<<overload forchar *, which does something entirely different (it expects a pointer to a null-terminated array of characters).Edit: In answer to your question about UB: The output operation performs an invalid pointer dereferencing (by assuming that
e->chpoints to a longer array of characters), which triggers the undefined behaviour.