Home > database >  Casting "char" pointer with "void*" and dereferencing it
Casting "char" pointer with "void*" and dereferencing it

Time:10-20

I think next part of a "cout" function yield incorrect result, I made casting with "void*" for a pointer and tried to get the value it saves.

 << "casted but for value: " << ((void*) (*s)) << endl;

in:

#include <iostream>
#include <cstring>

using namespace std;

int main(void)
{

char* s=(char*) malloc((12 1)*sizeof(char)); 

strcpy(s,"Hello World!");

cout << "direct value: " << s << endl
     << "casted for address: " << (void*) s << endl
     << "value by direct address calling: " << *s << endl
     << "casted but for value: " << ((void*) (*s)) << endl;

return 0;
}

Result:

pascal@pascal-Lenovo-ideapad-330-15AST:~/Computer/C  /Programs$ g   ./p10.cpp
./p10.cpp: In function ‘int main()’:
./p10.cpp:16:49: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
   16 |      << "casted but for value: " << ((void*) (*s)) << endl;
      |                                                 ^
pascal@pascal-Lenovo-ideapad-330-15AST:~/Computer/C  /Programs$ ./a.out
direct value: Hello World!
casted for address: 0x55aa8b248eb0
value by direct address calling: H
casted but for value: 0x48

CodePudding user response:

From the comments I noticed that the thought result as incorrect one is correct, because ((void*) (*s)) means the value of the pointer s without type (void), and this will give us the code Ascii in hexadecimal for the first character of the string recorded in the char pointer, so it's sensible result.

  • Related