有什么区别=指针
之间有什么区别:
int x = (int *)7;
到:
int x = 7;
谢谢
What the difference between:
int x = (int *)7;
to:
int x = 7;
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
之间有什么区别:
int x = (int *)7;
到:
int x = 7;
谢谢
What the difference between:
int x = (int *)7;
to:
int x = 7;
thanks
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(7)
首先,第一行无效。你不能将指针分配给 int (也就是说,你真的不应该。这是允许的,但没有意义)。
但不同之处在于,
(int*)7
表示“地址 7 处的整数”,而7
仅表示 7。First of all the first line is invalid. You can't assign a pointer to an int (which is to say, you really shouldn't. It is allowed, but it makes no sense).
However, the difference is that
(int*)7
means "the integer at address 7", and7
just means 7.警告:幽默的回答
WARNING: humourous answer
当您将指针分配给 int 时,第一个将导致编译器错误。指针(尤其是在 64 位领域)不等于整数。
确切的答案是第一个是将地址为7的指针分配给一个int,第二个只是分配一个int。
The first one will cause a compiler error as you are assigning a pointer to an int. Pointers (especially in 64-bit land) are not equivilent to integers.
The exact answer is the first is assigning a pointer with the address of 7 to an int, the second is just assigning an int.
没有实际差异,因为在第一个示例中,7 显式转换为 int *,然后隐式转换为 int 以匹配 x 的类型。然而,第一个例子是“坏代码”,因为它令人困惑。
There isn't a practical difference, because in the first example the 7 is explicitly cast to an int *, and then implicitly cast to an int to match x's type. However, the first example is "Bad Code" because it is confusing.
后者是有效的 C,它用值 7 初始化
int
变量x
。前者是一个编译时错误,许多编译器会错误地忽略它。您不能将指针分配给整型变量。
The latter is valid C that initializes an
int
variablex
with the value 7.The former is a compile-time error, which many compilers will erroneously ignore. You cannot assign a pointer to an integer variable.
第一个是错误的,您应该至少从编译器那里得到警告。
(int *)
类型的内容不应分配给int
。The first one is wrong and you should get a warning - at least- from your compiler. Something of type
(int *)
shouldn't be assigned toint
.第一个示例将地址存储在整数中,这不是类型安全的,也不是真正有效的(并且会在很多平台上崩溃)。您选择的地址与数字 7 具有相同的字节表示形式是偶然的。您可以轻松选择另一个地址,包括不适合“int”数据类型的地址。
第二个例子将一个整数存储在一个整数中,这是有效的。
每个可访问的内存块都有一个地址,而指针除了与该地址关联的数字之外什么也没有。如果你想在第一个例子中正确地“遍历地址”,它会是这样的:
不幸的是,上面的代码也无法编译,因为 C 缺乏获取与不关联的常量的地址的概念。姓名。
The first example stores an address in an integer, which is not type safe, is not really valid (and will break on a lot of platforms). That you chose an address which has the same byte representation as the number seven is happenstance. You could have easily chosen another address, including one that can't fit into an "int" data type.
The second example stores an integer in an integer, which is valid.
Every accessible memory chunk has an address, and a pointer is nothing except the number associated with that address. If you want to "walk through the address" properly in the first example, it would have been something like this:
Unfortunately, the above won't compile either, as C lacks the concept of taking the address of a constant not associated with a name.