再系统调用函数中,经常看到这样的情况:
传递结构体和字符串参数时,同时传递长度。
我们可以在程序中获得传入结构体和字符串的长度,为什么还要再传入一个长度?
原因在于:当传入的参数时字符串时我们可以轻易的获得长度,但是这个长度是用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
阅读(444) | 评论(0) | 转发(0) |