浅谈sscanf陷阱

sscanf虽然是个不错的函数,它可以很简单的将字符串转成特定的格式,比如转成整数、浮点数等等。但是如果使用不慎,会带来很大的麻烦。

今天笔者在使用sscanf时,就遇到了一个诡异的问题。

代码的书写如下:


//begin added by liuzhiyong 20160504
int HexToBin(char *src,char *bin,int length)
{
  int i = 0;
  int j = 0;
  printf("HexToBin src = %s length = %d\n",src,length);
  unsigned char temp;
  char buf[3]={0};
  for (i = 0;i < length; i+=2)
  {
	 strncpy(buf,src+i,2);	
	 buf[2] = 0;
	 sscanf(buf,"%x",&temp);
	 bin[j] = temp;
	 j++;
	printf("i = %d j = %d buf = %s temp = %d\n",i,j,buf,temp);
  }
  return 1;
}
//end 20160504

貌似没问题,但在实际调用的时候,陷入了死循环,经打印i的值始终为0.


通过分析,"%x"这个格式转化出来的值的类型是int,而且它会把后面的变量当成int来处理,而int的值在内存中为4个字节。而temp只是一个字节,sscanf将i的值也顺带赋值了,赋值为0.


了解到问题的根源后,将代码修改为:

//begin added by liuzhiyong 20160504
int HexToBin(char *src,char *bin,int length)
{
  int i = 0;
  int j = 0;
  printf("HexToBin src = %s length = %d\n",src,length);
  int temp;
  char buf[3]={0};
  for (i = 0;i < length; i+=2)
  {
	 strncpy(buf,src+i,2);	
	 buf[2] = 0;
	 sscanf(buf,"%x",&temp);
	 bin[j] = (unsigned char)temp;
	 j++;
	printf("i = %d j = %d buf = %s temp = %d\n",i,j,buf,temp);
  }
  return 1;
}
//end 20160504

问题得以解决。


你可能感兴趣的:(c/c++)