strlen( )与sizeof有什么不同

适用对象不同

  1. strlen()统计字符串常量个数,不包括空字符(\0);
  2. sizeof 统计的是所有常量(数字常量、表达式、基本类型,数组,结构体等)等的字节数。

strlen()原型

size_t strlen(char const* _Str);

参数是一个常量字符串指针,返回值是类型为size_t的字符串的长度(字符串长度不包括终止符)

sizeof()原型

返回名称所占字节数。对于数据类型必须用括号,而对于变量可以省略括号。如:sizeof(int)=sizeof(1)
sizeof array,sizeof(i)、sizeof i.

输出sizeof返回值

==C99中对于sizeof的返回值(实际上是无符号整型)用了专门的printf说明符”%zd”,其他系统可以尝试用”u”或者”lu”==

#include <stdio.h>
#include <string.h>
#define PRAISE "What a super marvelous name!"
int main(void)
{
    char name[40];

    printf("What's your name?\n");
    scanf("%s",name);
    printf("Hello,%s. %s\n",name,PRAISE);
    printf("Your name of %d letters occupies %d memory cells.\n",strlen(name),sizeof PRAISE);
    printf("The phrase of praise has %d letters",strlen(PRAISE));
    printf("and occupies %d memory cells.\n",sizeof PRAISE);

    return 0;
}

运行结果如下:

What’s your name?

Lxxxxxx

Hello,Lxxxxxx. What a super marvelous name!

Your name of 7 letters occupies 29 memory cells.

The phrase of praise has 28 lettersand occupies 29 memory cells.

猜你喜欢

转载自blog.csdn.net/weixin_39258979/article/details/79158516