#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'结尾。