简体   繁体   English

分配不同类型的指针

[英]Assigning pointers of different types

Why is the initialization of lp illegal?为什么lp的初始化是非法的?

int i = 42; 
long *lp = &i;

Xcode prompts that I cannot initialize a variable of type 'long *' with an rvalue of type 'int *'. Xcode 提示我无法使用“int *”类型的右值初始化“long *”类型的变量。

Why?为什么?

Your Xcode is on point, those are different types, it is indeed an illegal initialization, C++ does not allow for assignment (or initialization) of pointers with different types.您的 Xcode 是正确的,它们是不同的类型,这确实是非法初始化,C++ 不允许分配(或初始化)具有不同类型的指针。

That said, you can explicitly convert the assignee:也就是说,您可以显式转换受让人:

int i = 42; 
long *lp = reinterpret_cast<long*>(&i);

About your seach for reasoning, I'll say those are the rules of the language, they are there to protect you (and your program), not to make your job more difficult, a pointer to long used to operate (dereference, increment, etc.) in an address which is used to store an int will invoke undefined behavior .关于你的推理,我会说这些是语言的规则,它们是为了保护你(和你的程序),而不是让你的工作更困难,一个指向long用于操作的指针(取消引用,递增,等)在用于存储int的地址中将调用未定义的行为 A compiler is not obliged to treat pointers of different types in the same way.编译器没有义务以相同的方式处理不同类型的指针。 Differences in size, alignment, etc. can occur.可能会出现尺寸差异,alignment 等。

As largest_prime_is_463035818 stated the obligation to explicitly cast tries to prevent mistakes. 正如 maximum_prime_is_463035818 所述,明确强制转换的义务试图防止错误。

This, however, only allows you to compile your program, it doesn't remove the possibility of it being ill-formed.但是,这仅允许您编译程序,并不能消除程序格式错误的可能性。

Simple example:简单的例子:

int i = 42;   

int *p = &i;    
long *lp = reinterpret_cast<long*>(&i);
long *lpc = (long*)(&i); 

std::cout << "int pointer => " << *p << "\n";   // fine, prints 42
std::cout << "long pointer => " << *lp << "\n"; // not fine, prints random vaue *
std::cout << "long pointer 2 => " << *lpc << "\n"; // not fine, same *

As you can see in the example above your compiler was right, that is indeed a problematic cast, tricking the compiler to allow the conversion made the program compile, but fail to produce a consistent result.正如您在上面的示例中看到的,您的编译器是正确的,这确实是一个有问题的转换,欺骗编译器允许转换使程序编译,但无法产生一致的结果。

* I also tried this in a Windows platform and the results were good, maybe because a long in my platform is only 4 bytes, same as an int , maybe not, the point is, you only should do this when you are absolutely certain that the types are interchangeable. *我也在 Windows 平台上尝试过,结果很好,可能是因为我的平台中的long只有 4 个字节,与int相同,也许不是,关键是,只有当你绝对确定时才应该这样做类型是可以互换的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM