sizeof 使用


#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
using namespace std;


class A{};
class B{};
class C:public A,public B{};
class D:virtual public A{};
class E:virtual public A,virtual public B{};
class F{
//    char c1;
    virtual void fun(){}
};


void Function1(char p[], int num){
    cout << "F1: " << sizeof(p) << endl; // 4  数组在做为函数参数时均为指针
}

void Function2(int p[], int num){
    cout << "F2: " << sizeof(p) << endl; // 4  数组在做为函数参数时均为指针
}

int main(){
    char str1[] = "hello";
    cout << sizeof(str1) << endl; // 6 (自动加了'/0')
    cout << strlen(str1) << endl; // 5 字符串长度

    char str2[5] = {'h','e','l','l','o'};
    cout << sizeof(str2) << endl; // 5
    cout << strlen(str2) << endl; // 没有'\0' 未知,不确定

    int arr[] = {1,2,3};
    cout << sizeof(arr) << endl; // 12

    char *p1 = "hello";
    cout << sizeof(p1) << endl;  // 4  p1是一个指针,大小为4

    char *p2[] = {"hello","world"};
    cout << sizeof(p2) << endl;  // 8  p2是长度为2的指针数组

    int n = 10;
    cout << sizeof(n) << endl;  // 4

    int *p = &n;
    cout << sizeof(p) << endl;  // 4   p是一个指针,大小为4

    int *pp = (int *) malloc(100);
    cout << sizeof(p) << endl;  // 4   pp是一个指针,大小为4


    Function1(str1, 5);
    Function2(arr, 3);


    cout << sizeof(A) << endl;  //空类大小为1,编译器安插一个char给空类,用来标记它的每一个对象
    cout << sizeof(B) << endl;  //空类大小为1,编译器安插一个char给空类,用来标记它的每一个对象
    cout << sizeof(C) << endl;  //多继承或者多重继承后空类的大小还是1
    cout << sizeof(D) << endl;  //虚继承时编译器为该类安插一个指向父类的指针,指针大小为4
    cout << sizeof(E) << endl;  //指向父类A的指针与父类B的指针,加起来大小为8

    cout << sizeof(F) << endl;
}



注:sizeof与strlen的区别

  • sizeof是运算符, strlen是函数
  • sizeof测量的是字符分配的大小,strlen测量的是字符的实际长度
char str[20] = "hello";
 
printf("strlen: %d\n", strlen(str));  // 5
printf("sizeof: %d\n", sizeof(str));  // 20
  • 在子函数中,sizeof会把从主函数中传进来的字符数组当作指针来处理。指针的大小又是由机器来决定,而不是人为的来决定。
#include <stdio.h>
 
void size_of(char str[])
{
    printf("sizeof:%d\n", sizeof(str));
}
 
int main()
{
    char str[20] = "hello";
 
    size_of(str);
 
    return 0;
}

  • strlen函数求的是字符串的实际长度,它求得方法是从开始到遇到第一个'\0';如果字符数组初始化没有‘\0’, strlen得到的值可能就不会正确。
  • strlen的结果要在运行的时候才能计算出来,而sizeof一般在编译的时候就已经计算过了。
  • sizeof可以用类型做参数,strlen只能用char*作参数,且必须是以'\0'结尾。






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值