传递数据结构参数和字符串参数时,同时传递长度

再系统调用函数中,经常看到这样的情况:

传递结构体和字符串参数时,同时传递长度。

我们可以在程序中获得传入结构体和字符串的长度,为什么还要再传入一个长度?

原因在于:当传入的参数时字符串时我们可以轻易的获得长度,但是这个长度是用SIZEOF 还是STRLEN,其值是否有效?

传入的参数后,不论SIZEOF还是STRLEN其长度变为传输参数的实际长度,而不再是定义变量时内存分配的长度

看下面的例子:

 

#include < stdio.h >


struct  A {//参数中含有二进制数据

    
int a;
    
char sBuf[5];

}
a;

struct  B {//参数中无二进制数据
    char sBuf[5];
    
char str[5];

}
b;


void  test( char   * sBuf, int  n) {
    printf(
"%s ",sBuf);
    printf(
"n=%d ",n);
    printf(
"sizeof=%d,strlen=%d ",sizeof(sBuf),strlen(sBuf));
    printf(
" ");
}


void  testS( struct  A  * s, int  n, struct  B  * r, int  m) {
   printf(
"struct A s ");
    printf(
"sizeof=%d,n=%d ",sizeof(s),n);//传入后的有效数据长度,定义时分配的内存长度
    printf("sizeof(int)+sizeof(s.sBuf)=%d ",sizeof(s->a)+sizeof(s->sBuf));
    printf(
"sizeof(int)+strlen(s.sBuf)=%d ",sizeof(s->a)+strlen(s->sBuf));


   printf(
" struct B r ");
    printf(
"sizeof=%d,m=%d ",sizeof(r),m);
    printf(
"sizeof(r.str)+sizeof(r.sBuf)=%d ",sizeof(r->str)+sizeof(r->sBuf));
    printf(
"strlen(r.str)+strlen(r.sBuf)=%d ",strlen(r->str)+strlen(r->sBuf));

}




int  main() {
    
int n,m;
    a.a
=5;
    strcpy(a.sBuf,
"abc");
    n 
= sizeof(a);

    strcpy(b.sBuf,
"abc");
    strcpy(b.str,
"abc");
    m 
= sizeof(b);


    testS(
&a,n,&b,m);


    
char sBuf[5];
    strcpy(sBuf,
"abcd");
    n 
= strlen(sBuf);
     test(sBuf,n);
    
/*
    sBuf[0] = 56;
    sBuf[1] = 56;
    sBuf[2] = 56;
    sBuf[3] = 56;

    
*/

    sBuf[
0= 'a';
    sBuf[
1= 'b';
    sBuf[
2= 'c';
    sBuf[
3= 'd';

    n 
= strlen(sBuf);
    test(sBuf,n);
    n 
= sizeof(sBuf);
    test(sBuf,n);

    
return 1;

}
 

 

 

执行结果:

struct A s
sizeof=4,n=12
sizeof(int)+sizeof(s.sBuf)=9
sizeof(int)+strlen(s.sBuf)=7


struct B r
sizeof=4,m=10
sizeof(r.str)+sizeof(r.sBuf)=10
strlen(r.str)+strlen(r.sBuf)=6
abcd
n=4
sizeof=4,strlen=4


abcd
n=4
sizeof=4,strlen=4


abcd
n=5
sizeof=4,strlen=4

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值