https://www.nowcoder.com/discuss/418992
2020.5.4
- x86——32位
- x64——64位
sizeof
bool 1
char 1
short 2
int 4
long 4/8(Linux 64)
long long 8
float 4
double 8
T *p
p 4/8
*p sizeof(T)
sizeof运算,问了strlen和sizeof的区别
<4.9>sizeof 返回一条表达式/一个类型名字所占的字节数,是一种运算符
<3.5.2>所得的值是一个size_t类型,size_t是机器相关的无符号类型,被设计得足够大能表示内存中任意对象的大小,数组下标通常为size_t类型
- sizeof()是运算符,strlen()是库函数
- sizeof()在编译时计算,strlen()在运行时计算
- sizeof()计算出对象使用的最大字节数,strlen()计算字符串的实际长度
- sizeof()的参数类型多样化(数组,指针,对象,函数都可以),strlen()的参数必须是字符型指针(传入数组时自动退化为指针)
sizeof 不能用来返回动态分配的内存空间的大小
strlen
它的功能是:返回字符串的长度。
该字符串可能是自己定义的,也可能是内存中随机的,该函数实际完成的功能是从代表该字符串的第一个地址开始遍历,直到遇到结束符’\0’停止。返回的长度大小不包括‘\0’
sizeof
https://blog.csdn.net/szchtx/article/details/10230711
# include<iostream>
# include <cstring>
using namespace std;
struct A
{
int a;
bool b;
double d;
};
struct stu5
{
short i;
struct
{
char c;
int j;
} ss;
int k;
};
void fun(int a[10])
{
cout << "fun(int a[10]) sizeof(a): " << sizeof(a) << endl; //结果为4,常见的陷阱
}
int main()
{
int *p;
int a[10] = {0};
fun(a);
int b[10];
char str[] = "d\0aa";
char* c = "ascd";
int* d = new int[10];
int e = 1;double f = 1.1;
cout << "sizeof(bool): " << sizeof(bool) << endl;
cout << "sizeof(int): " << sizeof(int) << endl;
cout << "sizeof(double): "<< sizeof(double) << endl;
cout << "sizeof(p): "<< sizeof(p) << endl;
cout << "sizeof(*p): "<< sizeof(*p) << endl;
cout << "sizeof(a): " << sizeof(a) << endl;
cout << "sizeof(a): " << sizeof(a + 0) << endl;
cout << "sizeof(str): " << sizeof(str) << endl;
cout << "strlen(str): " << strlen(str) << endl;
cout << "sizeof(A): " << sizeof(A) << endl;
cout << "sizeof(stu5): " << sizeof(stu5) << endl;
cout << "sizeof(c): " << sizeof(c) << endl;
cout << "sizeof(d): " << sizeof(d) << endl;
cout << "sizeof(e + f): " << sizeof(e + f) << endl;
cout << "sizeof(e = e + f): " << sizeof(e = e + f) << endl;
cout << "sizeof(f = e + f): " << sizeof(f = e + f) << endl;
}
//输出结果
fun(int a[10]) sizeof(a): 8
sizeof(bool): 1
sizeof(int): 4
sizeof(double): 8
sizeof(p): 8
sizeof(*p): 4
sizeof(a): 40
sizeof(a + 0): 8
sizeof(str): 5
strlen(str): 1
sizeof(A): 16
sizeof(stu5): 16
sizeof(c): 8
sizeof(d): 8
sizeof(e + f): 8
sizeof(e = e + f): 4
sizeof(f = e + f): 8
https://blog.csdn.net/w57w57w57/article/details/6626840
-
sizeof 指针
32位4字节长度,64位8字节长度 -
sizeof 静态数组
数组总长度(string需要加上最后的'\0') -
注意数组退化为指针(在传递数组时,为避免拷贝太多数据而导致效率太低,只传递数组的首地址)的情况:
void fun(int a[10])
{
int n = sizeof(a); //结果为指针长度,常见的陷阱
}
struct A
{
int a;
double d;
bool b;
};
sizeof(A) //24
struct A
{
int a;
double d;
bool b;
};
sizeof(A) //16
struct stu5
{
short i;
struct
{
char c;
int j;
} ss;
int k;
};
sizeof(stu5) //16.里面的struct展开,字节数为4的倍数即可
数据对齐https://www.cnblogs.com/fengfenggirl/p/struct_align.html
-
sizeof 表达式
当表达式作为sizeof的操作数时,它返回表达式的计算结果的类型大小(未指定时返回所占字节最大的?) -
sizeof 类
https://blog.csdn.net/szchtx/article/details/10254007
网友评论