g4ur4v
g4ur4v

Reputation: 3288

difference between int* and char* in c++

#include <iostream>
using namespace std;

int main() {
    int * a[5];
    char * b[5];
    cout<<a[1]; // this works and prints address being held by second element in the array  
    cout<<b[1]; // this gives run time error . why ?
    return 0;
}

Can anyone please explain to me cout<<b[1] gives run-time error ? Shouldn't both int and char array behave similar to each other ?

Upvotes: 1

Views: 294

Answers (4)

Wojtek Surowka
Wojtek Surowka

Reputation: 20993

C++ (inheriting it from C) treats character pointers specially. When you try to print a[1] of type int* the address is printed. But when you try to print b[1] of type char* the iostream library - following the rest of the language - assumes that the pointer points to the first character of zero-terminated string of characters. Both your output statements are initialised behaviour, but in the case of char* crash is much more likely because the pointer is dereferenced.

Upvotes: 2

SergeyA
SergeyA

Reputation: 62563

As others have said, iostream formatted output operators consider char* to point to C-style string and attempt to access this string.

What others have not said so far, is that if you are interested in the pointer, you need to cast the pointer in question to void*. For example:

std::cout << static_cast<const void*>(buf[1]);

Upvotes: 3

Chip Grandits
Chip Grandits

Reputation: 357

An output stream such as cout gives special consideration to char * that it does not give to other pointers. For pointers other than char *, it will simply print out the value of the pointer as a hexadecimal address. But for char *, it will try to print out the C-style (i.e. null terminated array of char) string referred to by the char *. Therefore it will try to dereference the char pointer, as @AlexD points in the comment to your post.

Upvotes: 2

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385108

Because IOStreams are designed to treat char* specially.

char* usually points to a C-string, so IOStreams will just assume that they do and dereference them.

Yours don't.

Upvotes: 6

Related Questions