C/C++ char数组作为参数传递时,谨慎使用strlen和sizeof

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’哦

  • 7
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值