使用 "void*" 转换 "char" 指针并取消引用它
Casting "char" pointer with "void*" and dereferencing it
我认为“cout”函数的下一部分会产生不正确的结果,我用“void*”进行了指针转换并尝试获取它保存的值。
<< "casted but for value: " << ((void*) (*s)) << endl;
在:
#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;
}
结果:
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
从评论中我注意到不正确的思考结果是正确的,因为 ((void*) (*s))
表示没有类型 (void)
的指针 s
的值,这将给我们char指针中记录的字符串的第一个字符的十六进制Ascii代码,所以这是合理的结果。
我认为“cout”函数的下一部分会产生不正确的结果,我用“void*”进行了指针转换并尝试获取它保存的值。
<< "casted but for value: " << ((void*) (*s)) << endl;
在:
#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;
}
结果:
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
从评论中我注意到不正确的思考结果是正确的,因为 ((void*) (*s))
表示没有类型 (void)
的指针 s
的值,这将给我们char指针中记录的字符串的第一个字符的十六进制Ascii代码,所以这是合理的结果。