2 - sizeof strlen

2020-04-29  本文已影响0人  李伟13

https://www.nowcoder.com/discuss/418992


2020.5.4

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
它的功能是:返回字符串的长度。
该字符串可能是自己定义的,也可能是内存中随机的,该函数实际完成的功能是从代表该字符串的第一个地址开始遍历,直到遇到结束符’\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

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

上一篇 下一篇

猜你喜欢

热点阅读