Mr.Anubis
Mr.Anubis

Reputation: 5322

Weird output when printing char pointer from struct

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

Answers (3)

MK.
MK.

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

Kerrek SB
Kerrek SB

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

Ed Heal
Ed Heal

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

Related Questions