Fork me on GitHub

C/C++——sizeof and strlen

综述

strlen()求的是长度,针对的对象是字符串.

sizeof()求的是大小,针对的是类型。

首先要明确的一个概念是,strlen()是函数,而sizeof()表面看起来是函数,其本质是关键字

函数必须有()

我们在写代码的时候,对于没有参数的函数,再调用的时候还是要写成fun(),为啥必须带那个()呢?反正有没有参数,省掉()岂不是更好。

函数名本质上代表函数的地址,对于没有参数的函数,如果不写(),也是可以编译过的,只不过不能调用函数。

不带()源码:

#include <stdio.h>
void fun()
{
     printf("hello\n");
}
  
void main()
{
      fun;
     getchar();
}

运行结果:

带()源码:

#include <stdio.h>
void fun()
{
     printf("hello\n");
}
 
void main()
{
     fun();
     getchar();
}

以上实验说明,函数必须有()。

证明sizeof是个关键字

sizeof是个关键字,有没有()都可以。但是为了程序可读性,最好加上()

证明sizeof是个关键字,源码

#include <stdio.h>
 
void main()
{
     int a = 10;
     printf("%d\n",sizeof(a));
     printf("%d\n", sizeof a);
     printf("%d\n", sizeof(10));
     printf("%d\n", sizeof 10);
     printf("%d\n", sizeof(int));
     //printf("%d\n", sizeof int);错误写法
     getchar();
}

运行结果

区分数字0,字符0,字符'\0'

字符'0'和字符'\0'是完全不一样的东西,'\0'是字符串的终结者。但是字符'\0'和数字0是等价的。见代码

#include <stdio.h>
 
void main()
{
     /* 输出值5
     char str[10] = { 'h','e','0','l', 'o' };
     printf("%d\n", strlen(str));*/
     /*输出值2
     char str[10] = { 'h','e','\0','l', 'o' };
     printf("%d\n", strlen(str));*/
     /*输出值2
     char str[10] = { 'h','e',0,'l', 'o' };
     printf("%d\n", strlen(str));*/
     getchar();
}

strlen与sizeof区分

  char buf[] = { 'a','b','c' };
    //strlen(buf) 长度不一定
    //printf(buf)显式乱码
    //sizeof(buf)=3
    //不指定长度,没有0结束符,有都少个元素,sizeof就多长

    char buf1[10] = { 'a','b','c' };
    //strlen(buf1)=3
    //printf(buf1)=abc
    //sizeof(buf1)=10
    //指定长度,后面没有赋值的元素自动补0

    char buf2[10] = { 0 };
    //strlen(buf2)=0
    //printf(buf2)=无输出
    //sizeof(buf2)=10
    //指定长度,所有元素值都为'\0'

    char buf3[] = "hello";
    //strlen(buf3)=5
    //printf(buf3)=hello
    //sizeof(buf3)=6
    //"hello"尾部隐藏含有'\0'

    char buf4[] = "\0129"
    //strlen(buf4)=2
    //printf(buf4)=换行9
    //sizeof(buf4)=3
    //""里面遇到\0后面就不要再跟数字了,很可能遇到转移字符  \012就是换行符\n的arcii形式

 

posted @ 2018-07-22 22:08  克拉默与矩阵  阅读(246)  评论(0)    收藏  举报