sizeof(数组名) 及strlen(数组名)

#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  *)。 

 

func(char* p)
{
    strcpy(p, "1234");
}

int main()
{
    char ch[100] = {0};
    func(ch);
    a = sizeof(ch); 
    b = strlen(ch);   
  
    printf("a = %d, b = %d\n", a, b);      
}

 

运行结果:

a = 100, b = 4

 

 

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

posted @ 2013-06-28 11:29  奥卡姆剃刀  阅读(1374)  评论(0编辑  收藏  举报