长度为0的字符数组的赋值

结构体格式如下:

  struct  ss_t
 {
   short int totallen;
   short int command;
   char msg[0];
 };

 需要给结构体中的msg赋值,由于msg的长度为0,直接赋值时程序提示赋值错误,经过处理之后,可以使用以下方式赋值:

 int totallen;
 int command;
 char msg[] = "123456";
 int  testlen = sizeof(msg);
 char *buf;
 struct ss_t *st;

 buf = (char *)malloc(sizeof(char) * 100);
 if (buf == NULL) {
  return ;
 }
 memset(buf, 0, 100);

 totallen = strlen(msg);
 command = 1000;
 memcpy(buf, &totallen, sizeof(short int));
 memcpy(buf + sizeof(short int), &command, sizeof(short int));
 memcpy(buf + 2 * sizeof(short int), msg, strlen(msg)); 
 st = (struct ss_t *)buf;
 char showres[50]={0};
 char showmsg[50]={0};
 sprintf(showres,"st->s_id %d st->len %d\n", st->totallen, st->command);
 sprintf(showmsg,"st->msg %s\n", st->msg);   
 MessageBoxA(NULL,showres,showmsg,0);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值