Reputation: 5322
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?
Upvotes: 1
Views: 1035
Reputation: 34527
It will print 'a' followed by the garbage until it find a terminating 0. You are confusing a char type (single character) with char* which is a C-style string which needs to be null-terminated.
Note that you might not actually see 'a' being printed out because it might be followed by a backspace character. As a matter of fact, if you compile this with g++ on Linux it will likely be followed by a backspace.
Upvotes: 1
Reputation: 477070
You have to dereference the pointer to print the single char: std::cout << *e->ch << std::endl
Otherwise you are invoking the <<
overload for char *
, 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->ch
points to a longer array of characters), which triggers the undefined behaviour.
Upvotes: 4
Reputation: 60007
Is this a null
question.
Strings in C and C++ end in a null characher. x is a character but not a string. You have tried to make it one.
Upvotes: 0