sizeof如何区分数组和指针 [英] How sizeof differentiate between an array and a pointer

查看:308
本文介绍了sizeof如何区分数组和指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们将sizeof应用于数组名称时,它返回数组中的字节数,即元素数乘以单个元素的大小。

当sizeof应用于指针时,它返回指针的大小,即32位操作系统上的4个字节。

由于数组名称指向数组的第一个元素,即数组名称也是一种指针。那么,编译器如何区分操作数\\参数传递的是一个数组而不是一个指针?

解决方案

sizeof 运营商 [ ^ ],而不是函数。因此它表现依赖于上下文。如果您下载一个开源的c / c ++编译器并自行检查,您会注意到,有许多实际的sizeof运算符被声明,并且在某些情况下它更像是一个宏,而不是真正的运算符。


这就像问:编译器如何区分数组声明和指针一?

你知道,编译器解析源代码,它能够区分 sizeof 运算符的不同参数,因为编程语言不含糊。


< blockquote class =FQ>

Quote:

由于数组名称指向数组的第一个元素,即数组名称也是一种指针。



是和否。是的,在许多方面,您可以像指针一样使用数组名称。但不,这不会成为一个指针。有几个重要的区别:



1.您不能将另一个数组分配给数组名称。

2.因此,你不能在堆上分配数组。

3.同样,你不能删除免费数组名称。



数组是一种共享指针行为的类型,与 int <的方式相同/ code>变量和指针共享一些算术运算符。它们的类型仍然完全不同。





PS:

指针就像一个路牌一座城市。阵列就像一条街。虽然街道可能从街道标志的位置开始,但这并不能使标志成为街道。如果您查询标志的大小或街道的大小,您注意到差异! ;)

When we apply sizeof to an array name it returns the number of bytes in the array i.e. Number of elements multiplied by the size of individual element.
When sizeof is applied to a pointer it returns the size of a pointer i.e. 4 byte on 32 bit OS.
Since the array name points to the first element of the array, i.e array name is also a kind of pointer. So how the compiler\sizeof differentiate that the operand\parameter passed is an array not a pointer?

解决方案

sizeof is an operator[^], not a function. Thus it "behaves" context dependent. If you download an open source c/c++ compiler and check for yourself, you will notice, that there are many actual sizeof operators declared, and in some cases it is more a macro, than a real operator.


This is like asking: "How the compiler differentiate between an array declaration and a pointer one?"
You know, the compiler parses the source code and it is able to differentiate the different arguments of sizeof operator because the programming language is not ambiguous.


Quote:

Since the array name points to the first element of the array, i.e array name is also a kind of pointer.


Yes and no. Yes, in many ways, you can use the array name like a pointer. But no, that doesn't make it a pointer. There are a couple of important distinctions:

1. You cannot assign another array to an array name .
2. As a consequence, you cannot allocate an array on the heap.
3. Likewise, you cannot delete or free an array name.

An array is a type that shares some of the behaviour of a pointer, in the same way that int variables and pointers share some of their arithmetic operators. They're still quite different types.


P.S.:
A pointer is like a street sign in a city. An array is like a street. While the street may start at the position of the street sign, that doesn't make the sign a street. And if you query the size of the sign, or the size of the street, you will notice a difference! ;)


这篇关于sizeof如何区分数组和指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆