现在的位置: 首页 > 综合 > 正文

sizeof(数组名)

2018年02月01日 ⁄ 综合 ⁄ 共 700字 ⁄ 字号 评论关闭

#include <iostream>
using namespace std;
void theFun(char a[])
{
cout<< "2: " <<sizeof(a) <<endl;
}
int main()
{
char a[100]=" ";
cout<< "1: "<<sizeof(a) <<endl;
theFun(a);
cout<< "3: "<<sizeof(a[100]) <<endl;
return 0;
}

程序的输出结果为:
1:100
2:4
3:1 //相当于a[100]这个数所占的字节大小,也就是一个char字节占得大小
当数组作为函数的参数进行传递时,该数组自动退化为同类型的指针。不论数组a的容量是多少,sizeof(a)始终等于sizeof(char *)。
if 数组名直接作为参数压栈
then sizeof(数组名) = 一个指针所占字节数
else sizeof(数组名) = 数组所占字节数
测试程序如下:

typedef struct{
char array[32];
}node_t;

void fun1(node_t node)
{
printf("%d/n", sizeof(node.array));
}

void fun2(char array[32])
{
printf("%d/n", sizeof(array));
}

int main(void)
{
node_t node;
fun1(node); // indirect
fun2(node.array); // direct

return 0;
}程序的输出是:
32
4
文章出处:DIY部落(http://www.diybl.com/course/3_program/c++/cppjs/20091120/182930.html)

抱歉!评论已关闭.