sizeof用法

sizeof()功能:计算数据空间的字节数
 
1.数组的sizeof操作
  对于静态数组,sizeof可直接计算数组大小,
    例1:int a[10];char b[]="hello";
    sizeof(a)等于4*10=40;
    sizeof(b)等于6;
    例2:har str[] = "hdghdghjjhj"; sizeof (str )=12
  注意:数组做型参时,数组名称当作指针使用!!
  void fun(char p[])
  {
    sizeof(p)等于4;
  }
2.指针的sizeof操作
  指针均可看为变量类型的一种。所有指针变量的sizeof 操作结果均为4。
 例:int *p; sizeof(p)=4;
  但sizeof(*p)相当于sizeof(int);
3.使用string的注意事项
  string s="hello";
  sizeof(s)等于string类的大小,sizeof(s.c_str())得到的才是字符串长度。
 
例:
#include "stdafx.h"

#include<iostream>
#include<string>
using namespace std;


void Foo ( char str[100]){
    cout<<"Foo ( char str[100])中的sizeof( str ) =" <<sizeof( str ) <<endl;
}

int main(int argc, char* argv[])
{
    printf("Hello World!\n");
    
    char str[] = "hdghdghjjhj";
    char *p = str ;
    int n = 10;
    cout<<"sizeof (str ) =" <<sizeof (str )<<endl;
    cout<<"sizeof ( p ) =" <<sizeof ( p )<<endl;
    cout<<"sizeof ( n ) =" <<sizeof ( n ) <<endl;
    
    
    void *ptr = malloc( 100 );
    cout<<"sizeof ( ptr ) = " <<sizeof ( ptr )<<endl;
    
    Foo(str);
    
    int a[10];
    cout<<"sizeof ( a ) =" <<sizeof ( a ) <<endl;

    string s = "hellogfdgdfgfg";
    cout<<"sizeof (string s ) =" <<sizeof ( s ) <<endl;
    cout<<"sizeof(s.c_str()) = "<<sizeof(s.c_str())<<endl;

    return 0;
}

 

posted @ 2012-09-12 21:49  Rookie_h  阅读(282)  评论(0编辑  收藏  举报