void pointer not printing?

I'm trying to just simply print the contents of dat
and then try to dereference it but nothing gets printed, instead I'm guessing an exception is bring thrown as the process returns - (0xC0000005)

I can't see what I'm doing wrong here, something that looks so routine seems to be catching me up, I convert a void pointer to a char pointer surely this is a legal operation?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  #include <iostream>

using namespace std;

void example(void* data,int size){

    char* dat = (char*)data;
    char* end = dat + size;

    cout << dat << endl;
    cout << *dat << endl;

}
int main()
{
    char letter = 'a';
    example((void*)letter,8);
}


edit* I'm not thinking straight right now :/ I forgot the address of operator

should be

1
2
3
char letter = 'a';
example((void*)&letter,8);
Last edited on
Your dat variable is not pointing to a null-terminated char array. Line 10 is undefined behavior.
Last edited on
I'm not thinking straight right now :/ I forgot the address of operator

Use C++ style casts and never make that mistake again
@Ganado that is very true, just re looking at it,

so when cout is given a char* as an argument it prints the data like a string? what I was expecting was for it to print dats's memory address.
Yes, the overload for ostream operator << treats char* as a null-terminated c-string to allow things like,
cout << "Hello";
to be possible.

Cast to void* to print address.
Topic archived. No new replies allowed.