char[],char*做参数
函数参数中定义的数组会退化为指针,使用sizeof测试数组类型的参数大小时得到的并不是整个数组的字节数,而是指针的字节数。看如下验证代码
void test(char str1[],char *str2)
{
int temp1=sizeof(str1);
int temp2=sizeof(str2);
int temp3=strlen(str1);
int temp4=strlen(str2);
printf("length is %d,%d\n",temp1,temp2);
}
int main()
{
char a[10];
char *b="string";
test(a,b);
return 0;
}
编译
g++ -o test.exe test.cpp
输出
test.cpp: In function 'void test(char*, char*)':
test.cpp:8:26: warning: 'sizeof' on array function parameter 'str1' will return size of 'char*' [-Wsizeof-array-argument]
int temp1=sizeof(str1);
^
test.cpp:6:16: note: declared here
void test(char str1[],char *str2)
~~~~~^~~~~~
test.cpp: In function 'int main()':
test.cpp:18:13: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
char *b="string";
^~~~~~~~
执行
./test.exe
输出
size is 8,8
strlen is 0, 6
由编译的输出可见,其sizeof实际上返回的是char*的size
而strlen是根据’\0’的位置来进行长度计算。
如果数组参数的长度需要在函数中被使用时,最好的做法是将数组的长度也作为参数传入函数中。如
// 为了防止被误解,最好使用指针来替代数组做参数
void copy_hello_world(char *str, int str_length)
{
strncpy(str, "hello world!", str_length - 1);
}
int main()
{
char a[10] = { 0 };
// 为了防止被误解,最好使用指针来替代数组做参数
copy_hello_world(a, sizeof(a));
printf("%s\n", a);
return 0;
}
输出
$ gcc -o main main.c
$ ./main
hello wor
因为我们传入的数组只有10个字节,因此只能拷贝到第九个byte即r,a的最后一个字节是’\0’哦