sizeof 与 strlen 的区别及使用

1、问题描述

What is the output of the following code?

#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{

    char *ss1 = "0123456789";
    char ss2[] = "0123456789";
    char *str1 = (char*)malloc(100);
    void *str2 = (void *)malloc(100);

    cout << sizeof(ss1) << endl;
    cout << sizeof(ss2) << endl;
    cout << sizeof(str1) << endl;
    cout << sizeof(str2) << endl;

    return 0;
}

2、结果

4
11
4
4

3、析

对于指针,sizeof操作符返回这个指针占的空间,一般是4个字节;而对于一个数组,sizeof返回这个数组所有元素占的总空间。

char * 与 char[] 容易混淆,而且 char *p = "aa"; 这样的写法现在不被提倡,应尽量避免这样使用。

而strlen是不区分是数组还是指针的,就读到 为止返回长度。而且strlen 是不把 计入字符串的长度的。

原文地址:https://www.cnblogs.com/aqing1987/p/4186113.html