东营网站设计公司百度首页排名怎么做到
1 .strlen
C库函数size_t strlen(const char* str)计算字符串str的长度,直到空字符,不包括空字符。在C语言中,字符串实际上是使用空字符\0结尾的一维字符数组。空字符(Null character)又称结束符,缩写NUL,是一个数值为0的控制字符,\0是转义字符,意思是告诉编译器,这不是字符0,而是空字符。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>int main() {char str[10];str[0] = 0;printf("strlen(str):%d\n",strlen(str));printf("%s\n",str);//此时str是一个空字符串//sizeof(str)返回的是字符数组的大小printf("sizeof(str):%d\n",sizeof(str));return 0;
}
输出
strlen(str):0sizeof(str):10
再看把str设置为长度为9的字符串的情况
#include <stdio.h>
#include <stdlib.h>
#include <string.h>int main() {char str[10]="123456789";printf("strlen(str):%d\n",strlen(str));printf("%s\n",str);//此时str是一个空字符串//sizeof(str)返回的是字符数组的大小printf("sizeof(str):%d\n",sizeof(str));if(str[9] == 0)printf("str[9] is NUL");return 0;
}
输出
strlen(str):9
123456789
sizeof(str):10
str[9] is NUL
如果不给空字符留一个位置,会报错:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>int main() {char str[10]="1234567899";printf("strlen(str):%d\n",strlen(str));printf("%s\n",str);//此时str是一个空字符串//sizeof(str)返回的是字符数组的大小printf("sizeof(str):%d\n",sizeof(str));if(str[9] == 0)printf("str[9] is NUL");return 0;
}
报错:
main.cpp:6:18: error: initializer-string for char array is too longchar str[10]="1234567899";^~~~~~~~~~~~
main.cpp:7:31: warning: format specifies type 'int' but the argument has type 'size_t' (aka 'unsigned long') [-Wformat]printf("strlen(str):%d\n",strlen(str));~~ ^~~~~~~~~~~%zu
main.cpp:10:31: warning: format specifies type 'int' but the argument has type 'unsigned long' [-Wformat]printf("sizeof(str):%d\n",sizeof(str));~~ ^~~~~~~~~~~%lu
2 warnings and 1 error generated.
2.strcat
strcat函数原型是char *strcat(char *dest,const char *src)。
传入的dest必须是以NUL结尾的合法的字符串。如果dest不是以NUL结尾的字符串,会导致未定义行为,具体效果看编译器的实现。
错误示例:
#include <stdio.h>
#include <string.h>int main() {char str1[10];for(int i = 0;i < 10;i++)str1[i] = -1;char str2[10] = "123456789";//错误示例strcat(str1,str2);printf("str1:%s\n",str1);return 0;
}
Ubuntu 20.04.6 LTS +gcc (Ubuntu 9.4.0-1ubuntu1~20.04.2) 9.4.0,效果如下:
str1:����������123456789123456789
*** stack smashing detected ***: terminated
Aborted