sizeof的数组和指针 [英] Sizeof arrays and pointers

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

问题描述

下面是我的示例code

Here is my sample code

#include<stdio.h>
void main()
{
 int arr[]={1,2,3,4,5,6};
 char *ptr,a;
 a='c';
 ptr=&a;
 int *ptr1,a1;
 a1=4;
 ptr1=&a1;
 printf("%d  %d   %d",sizeof(arr), sizeof(ptr1), sizeof(ptr));
}

现在,据我了解,规模会告诉我来存储变量,需要的尺寸,现在输出的这个人是

Now, as far as I understand, size of will tell me the size required to store the variable, now the output for this one is

24 4 4

为什么是大小 ARR = 24 ,毕竟它只是一个指针,它应该有大小= 4?

Why is the size of arr=24, after all it's just a pointer and it should be having size =4 ?

感谢。

推荐答案

......毕竟它只是一个指针......?号数组不是指针。数组是一个数组对象:存储了坚实的连续块存储数组元素,不涉及任何形式的指针。在你的情况数组的大小为4的各6片。这就是为什么你的的sizeof 计算结果为24。

"...after all it's just a pointer..."? No. Array is not a pointer. Array is an array object: a solid continuous block of memory that stores the array elements, no pointers of any kind involved. In your case array has 6 elements of size 4 each. That is why your sizeof evaluates to 24.

有关数组的指针是常见的误解已经被揭穿了数百万次,但不知何故,继续现在,然后弹出。阅读常见问题解答,回来如果您有任何关于它的问题。

The common misconception about arrays being pointers has been debunked millions of times, but somehow it continues to pop up now and then. Read the FAQ, come back if you have any questions about it

http://c-faq.com/aryptr/index.html

P.S。由于@Joachim Pileborg在他的回答正确地指出,的sizeof 不是一个函数。这是一个运营商。

P.S. As @Joachim Pileborg correctly noted in his answer, sizeof is not a function. It is an operator.

在该阵列由指针表现不同的另一个背景是一元&安培; 经营者(经营者地址)。当一元&安培; 应用于类型的指针为int * 是生产类型的指针 INT ** 。当一元&安培; 应用于类型的数组 INT [10] 是一家生产型的指针 INT(*)[10] 。这是两个非常不同的类型。

Another context in which arrays behave differently from pointers is the unary & operator (the "address of" operator). When unary & is applied to a pointer of type int * is produces a pointer of type int **. When unary & is applied to an array of type int [10] is produces a pointer of type int (*)[10]. These are two very different types.

int *p = 0;
int a[10] = { 0 };

int **p1 = &p;      /* OK */
int **p2 = &a;      /* ERROR */
int (*p3)[10] = &a; /* OK */

有问题(和错误)另一种流行来源:有时人们期待&安培; 来产生 INT ** 在应用到 INT [10] 数组指针。

It is another popular source of questions (and errors): sometimes people expect & to produce a int ** pointer when applied to an int [10] array.

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

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