> 文章列表 > C语言-字符串

C语言-字符串

C语言-字符串

sizeof和strlen 的区别:

区别1:

        1.sizeof计算整个数组大小,

        2.strlen 计算有效的数组大小

新建字符数组”hello“

    char cdata[128]="hello";
    printf("sizeof--cdata的长度:%d\\n",sizeof(cdata));
    printf("strlen--cdata的长度: %d\\n",strlen(cdata));

输出结果:

sizeof--cdata的长度:128
strlen--cdata的长度: 5

 

区别2:

        1.指针 char *p2,sizeof计算指针的时候,得出的是多少字节来表示一个地址

        2.strlen计算的是指针指向字符串数组的长度   

新建指针字符数组

    int *p1;
    char *p2="hello";
    void (*pfunction)();//定义函数指针
    pfunction=functionTest;//保存地址

    puts("区别2:");
    //指针 char *p2,sizeof计算指针的时候,得出的是多少字节来表示一个地址
    printf("sizeof:p2 的长度:          %d\\n",sizeof(p2));
    printf("sizeof:char * 的长度:      %d\\n",sizeof(char *));
    printf("sizeof:int * 的长度:       %d\\n",sizeof(int *));
    printf("sizeof:char 的长度:        %d\\n",sizeof(char));
    printf("sizeof:functionTest 的长度:%d\\n",sizeof(functionTest));//函数名长度
    printf("sizeof:pfunction 的长度:   %d\\n",sizeof(pfunction));//指针
    //strlen计算的是指针指向字符串数组的长度    
    printf("strlen:p2 的长度:          %d\\n",strlen(p2));

输出结果:

区别2:
sizeof:p2 的长度:          8
sizeof:char * 的长度:      8
sizeof:int * 的长度:       8
sizeof:char 的长度:        1
sizeof:functionTest 的长度:1
sizeof:pfunction 的长度:   8
strlen:p2 的长度:          5

代码实例:

#include<stdio.h>
#include<string.h>
/*c
*/
void functionTest()
{}
int main()
{char cdata[128]="hello";//区别1:puts("区别1:");printf("sizeof--cdata的长度:%d\\n",sizeof(cdata));//计算整个数组大小printf("strlen--cdata的长度: %d\\n",strlen(cdata));//计算有效的数组大小//区别2:int *p1;char *p2="hello";void (*pfunction)();//定义函数指针pfunction=functionTest;//保存地址//(*pfunction)();//调用puts("区别2:");//指针 char *p2,sizeof计算指针的时候,得出的是多少字节来表示一个地址printf("sizeof:p2 的长度:          %d\\n",sizeof(p2));printf("sizeof:char * 的长度:      %d\\n",sizeof(char *));printf("sizeof:int * 的长度:       %d\\n",sizeof(int *));printf("sizeof:char 的长度:        %d\\n",sizeof(char));printf("sizeof:functionTest 的长度:%d\\n",sizeof(functionTest));//函数名长度printf("sizeof:pfunction 的长度:   %d\\n",sizeof(pfunction));//指针//strlen计算的是指针指向字符串数组的长度	printf("strlen:p2 的长度:          %d\\n",strlen(p2));return 0;
}

 结果输出: