Reputation: 3288
#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
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
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
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
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