在未签名的char上的位XOR正在终止程序而没有错误
我正在尝试在C ++中创建一个64位的整数,我知道这已经存在于C标题stdint.h中,但我认为这可能是一个有趣的挑战。
无论如何,我正在尝试对三个无符号字符进行位XOR操作,并且该程序在没有警告的情况下停止,它只是停止一秒钟,然后停止:
unsigned char* a = (unsigned char*) 1;
unsigned char* b = (unsigned char*) 2;
unsigned char* c = (unsigned char*) 3;
unsigned char* result = (unsigned char*) malloc(sizeof(unsigned char));
std::cout << "Trying" << std::endl;
*result = *a ^ *b ^ *c;
std::cout << "Done!" << std::endl;
输出为:
PS C:\Users\super\Desktop> ./test.exe
Trying
PS C:\Users\super\Desktop>
我使用Windows 10,如果有帮助,请让我知道您是否需要其他信息,并感谢您的任何帮助,您可以给我:)
I'm trying to create a 64 bit integer as class in C++, I know this already exists in the C header stdint.h but I thought it could be a fun challenge.
Anyway, I am trying to perform a bitwise XOR operation on three unsigned chars, and the program keeps stopping without warning, it just pauses for a split second and then stops:
unsigned char* a = (unsigned char*) 1;
unsigned char* b = (unsigned char*) 2;
unsigned char* c = (unsigned char*) 3;
unsigned char* result = (unsigned char*) malloc(sizeof(unsigned char));
std::cout << "Trying" << std::endl;
*result = *a ^ *b ^ *c;
std::cout << "Done!" << std::endl;
The output being:
PS C:\Users\super\Desktop> ./test.exe
Trying
PS C:\Users\super\Desktop>
I am using Windows 10 if that helps, let me know if you need any other information, and thanks for any help you can give me :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在试图解释无效的指针。您想摆脱很多
*
s。为此,为什么要在堆上分配单个字节(
sizeof(unsigned char)
是1
)?您也可以将另一个unsigned char
变量变量。编辑注意:您还不需要使用
std :: endl :: endl
。You're trying to dereference invalid pointers. You want to get rid of a lot of those
*
s.Why are you allocating a single byte (
sizeof(unsigned char)
is1
by definition) on the heap for the result? You could just make that anotherunsigned char
variable, too.Editorial note: you also don't need to use
std::endl
.您的代码崩溃了,因为您正在删除指针
a
, b ,c
没有指向可以从可以读取的有效内存地址。carl的答案向您展示了如何重写此代码以完全不使用指针来,,<代码> b ,
c
。但是,如果出于某种原因,您实际上确实需要将整数传递为指针的类型(例如,因为您正在通过需要此的C API传递它们),那么您需要 type-cast 指针重新回到整数中,而不是解雇 Pointers,例如:
Your code is crashing because you are dereferencing pointers
a
,b
,c
which are not pointing at valid memory addresses that can be read from.Carl's answer shows you how to rewrite this code to not use pointers at all for
a
,b
,c
.But, if for some reason, you actually did need to pass around integers type-casted as pointers (for instance, because you are passing them through a C API that requires this), then you need to type-cast the pointers back into integers, not dereference the pointers, eg: