zoukankan      html  css  js  c++  java
  • C++基础--sizeof和strlen的区别

    首先,来运行一段程序:

    #include "stdafx.h"
    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
        char *a  = "aaaa";
        int x = sizeof(a);
        int y = strlen(a);
    
        printf("%d
    ", x);
        printf("%d
    ", y);
        
        return 0;
    }
    

     运行结果为:

    再看下面这段程序:

    #include "stdafx.h"
    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
        char *a  = "aaa";
        int x = sizeof(a);
        int y = strlen(a);
        int s = sizeof(char *);
        int s1 = sizeof(char);
        //int s2 = strlen(char*);
    printf(
    "%d ", s); printf("%d ", s1); printf("%d ", x); printf("%d ", x); return 0; }

    运行结果为:

    以上结果表示char*占用的内存大小为4, char占用的内存大小为1;

    运行以上两个程序,可以总结出sizeof和strlen的区别为:

    1. sizeof的参数可以是数据类型,也可以是变量,而strlen只能以以''结尾的字符串作为参数;

    2. sizeof计算的是数据类型占内存的大小,strlen计算的是字符串实际的长度

    3. sizeof是操作符,strlen是string的库函数;编译器是编译时就计算出了sizeof的结果,而strlen只有在运行时才计算;

    4. sizeof的参数为原参数,strlen的参数会变化为指针

  • 相关阅读:
    C#:反射
    静态和非静态类
    数据的存入取出(注册机方式)
    退出unity运行
    网络流基础
    欧拉回路
    博弈论问题
    洛谷P5304 [GXOI/GZOI2019] 旅行者
    [ZJOI2006]物流运输
    POJ3278 Catch that cow
  • 原文地址:https://www.cnblogs.com/anlia/p/5939600.html
Copyright © 2011-2022 走看看