sizeof strlen 詳細用法
- sizeof定義
- 記憶體對齊
- 代碼詳解
sizeof定義
關于sizeof運算子,《c++ primer》在139頁中是這樣說明的:
- 對char或者型別為char的運算式執行sizeof運算,結果得1;
- 對參考型別執行sizeof運算得到被參考物件所占空間的大小;
- 對指標執行sizeof()運算得到指標本身所占空間的大小;
- 對解參考執行sizeof()運算得到指標指向的物件所占空間的大小,指標不需要有效,
在sizeof的運算物件中解參考一個無效指標仍然是一種安全的行為,因為指標實際上并沒有
真正使用,sizeof不需要真的解參考也能知道它所指物件的型別, - 對陣列執行sizeof運算得到整個陣列所占的空間的大小,等價于對陣列中所有的元素
各執行一次sizeof運算并將所得結果求和,因此,值得注意的是,sizeof運算不會把陣列轉換
成指標來處理,同時,執行sizeof運算能得到整個陣列的大小,所以可以用陣列的大小除以
單個元素的大小得到陣列中元素的個數, - 對string物件或vector物件執行sizeof運算與計算struct時相同,都是根據自身成員變數來計算,為固定值(不同編譯器可能略有不同)
記憶體對齊
記憶體對齊適用于類,結構體
第一條:第一個成員的首地址為0
第二條:每個成員的首地址是自身大小的整數倍
第二條補充:以4位元組對齊為例,如果自身大小大于4位元組,都以4位元組整數倍為基準對齊,
第三條:最后以結構總體對齊,
第三條補充:以4位元組對齊為例,取結構體中最大成員型別倍數,如果超過4位元組,都以4位元組整數倍為基準對齊,(其中這一潭訓有個名字叫:“補齊”,補齊的目的就是多個結構變數挨著擺放的時候也滿足對齊的要求,)
代碼詳解
#include<iostream>
#include<string>
#include<vector>
#include<map>
using namespace std;
void func1(char a[]) {
cout <<"形引陣列:" <<sizeof(a) << endl;
}
int main() {
cout <<"int: "<< sizeof(int) << endl;//4
cout << "double: " << sizeof(double) << endl;//8
cout << "char: " << sizeof(char) << endl;//1
cout << "size_t: " << sizeof(unsigned int) << endl;//4
cout << "long int: " << sizeof(long int) << endl;//4
cout << "long long int: " << sizeof(long long int) << endl;//8
const char* str1 = "abcdef";
cout <<"str1: " <<sizeof(str1) << " " << sizeof(*str1) << " "<< strlen(str1) << endl;//4 1 6
char str2[] = "abcdef";
cout << "str2: " << sizeof(str2) << " " << sizeof(*str2) << " " << strlen(str2) << endl;//7 1 6
char str3[10] = "abcdef";
cout << "str3: " << sizeof(str3) << " " << sizeof(*str3) << " " << strlen(str3) << endl;//10 1 6
func1(str2);//4
func1(str3);//4
const char* b = "helloworld";
char* c[10];
double* d;
int** e;
void (*pf)();
cout << "char *b " << sizeof(b) << endl;//指標指向字串,值為4
cout << "char *b " << sizeof(*b) << endl; //指標指向字符,值為1
cout << "double *d " << sizeof(d) << endl;//指標,值為4
cout << "double *d " << sizeof(*d) << endl;//指標指向浮點數,值為8
cout << "int **e " << sizeof(e) << endl;//指標指向指標,值為4
cout << "char *c[10] " << sizeof(c) << endl;//指標陣列,值為40
cout << "void (*pf)() " << sizeof(pf) << endl;//函式指標,值為4
struct stu1 {
char c;
int i;
};
cout <<"stu1: " <<sizeof(stu1) << endl;//8
/*
#pragma pack(1)
struct stu2 {
char c;
int i;
};
cout << "stu2: " <<sizeof(stu2) << endl; //5
*/
struct stu3 {
char str[10];
int i;
char c;
};
cout << "stu3: " << sizeof(stu3) << endl;//20
union u
{
int a;
float b;
double c;
char d;
};
cout << "union: " << sizeof(u) << endl; //8
vector<int> v;
vector<string> vs;
cout <<"vector: " <<sizeof(v)<<" " << sizeof(vs) << endl;
string s;
cout << "string: " << sizeof(s) << endl;
map<int,int> m;
cout << "map: " << sizeof(m) << endl;
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/279363.html
標籤:其他
下一篇:大話測驗六技——讓測驗不要太容易
