数组作为函数参数传递时退化为指针(腾讯)
对字符串进行 sizeof 操作的时候,会把字符串的结束符“\0”计算进去的;
进行 strlen操作求字符串的长度的时候,不计算\0 的。
数组作为函数参数传递的时候,已经退化为指针了,Func 函数的参数 str_arg 只是表示一个指针,那个 100 不起任何作用的。改成void Func(char str_arg[2]),输出结果不变。
#include <iostream> #include <stdio.h> using namespace std; void Func(char str_arg[100]){ printf("%d\n",sizeof(str_arg));//4 printf("%d\n",strlen(str_arg));//5 } int main(){ char str[]="Hello"; printf("%d\n",sizeof(str));//6 printf("%d\n",strlen(str));//5 char *p=str; printf("%d\n",sizeof(p));//4 Func(str); }
输出:6 5 4 4 5
#include <iostream> #include <stdio.h> using namespace std; void Func(char str_arg[100]){ printf("%d\n",sizeof(str_arg)); printf("%d\n",strlen(str_arg)); } int main(){ char str[100]="Hello"; printf("%d\n",sizeof(str));//100 printf("%d\n",strlen(str)); char *p=str; printf("%d\n",sizeof(p)); Func(str); }
输出:100 5 4 4 5