为什么数组指针的大小在C中始终为8? [英] Why the size of pointer to array is always 8 in C?

查看:242
本文介绍了为什么数组指针的大小在C中始终为8?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是简单的代码,用于比较数组本身的大小和指向数组的指针的大小.

Belows are simple code that compares size of array itself and size of pointer to array.

#include <stdio.h>    
int main(){   
        int kkarray[100]= {1,0,};
        int (*kkpointer) = kkarray;

        printf("size of array using array itself : %ld \n" , sizeof(kkarray));        
        printf("size of array using pointer to array : %ld \n" , sizeof(kkpointer));   
}

但结果是

400
8

我可以理解,第一个值是400,但是第二个值也应该是400,因为当我分配了一个指向数组的指针kkpointer时,它的作用类似于数组的名称,即const地址值.例如,我可以使用kkpointer [0]获得数组的第一个值. 我想知道为什么我得到'8'而不是400. 我认为"8"不是地址本身的大小. 请让我知道.谢谢

I could understand that the first value is 400, but second one,, i think that it also should be 400 because as i assigned a pointer that points to array, kkpointer, it kinda acts like name of array, which is const address value. For example, i can get the first value of array using kkpointer[0]. I want to know why i got '8' instead of 400. I don't think the '8' is the size of address itself. please let me know. Thanks

推荐答案

任何指针的大小在您的平台上始终为8 ,因此它取决于平台.

The size of any pointer is always 8 on your platform, so it's platform dependent.

sizeof运算符不在乎指针所指向的位置,它给出了指针的大小,在第一种情况下,它只是给出了数组的大小,这并不相同.

The sizeof operator doesn't care where the pointer is pointing to, it gives the size of the pointer, in the first case it just gives the size of the array, and that is not the same.

这是来自§的引用. 6.5.3.4 ¶ 2 N1570草案

This is a quote from § 6.5.3.4, ¶ 2 N1570 draft

sizeof运算符产生其操作数的大小(以字节为单位),可能是 表达式或类型的括号名称. 大小由以下类型决定 操作数.结果是一个整数.如果操作数的类型是可变长度数组 类型,对操作数求值;否则,将不对操作数求值,并且结果为 整数常数

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant

§ 6.5.3.4 ¶ 4

将sizeof应用于类型为char,unsigned char或 签名的字符(或其限定版本),结果为1.应用于 具有数组类型的操作数,结果是数组中的字节总数 .103) 应用于具有结构或联合类型的操作数,结果是 这样的对象中的字节,包括内部填充和结尾填充

When sizeof is applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1. When applied to an operand that has array type, the result is the total number of bytes in the array.103) When applied to an operand that has structure or union type, the result is the total number of bytes in such an object, including internal and trailing padding

如您所见,

应用于数组时,它给出了总字节数.但是,如果传递指针,则结果将是其类型的大小.

so as you can see, when applied to the array, it gives the total bytes. But if you pass a pointer, then the result will be the size of it's type.

这篇关于为什么数组指针的大小在C中始终为8?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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