我想将一个字符串(例如“ 00-00-CA-FE-BA-BE”)转换为无符号char ch [6]数组。我尝试使用sscanf
,但是由于任何原因,变量macAddress之后由于堆栈损坏而导致崩溃。
我猜想格式说明符有些问题,但我似乎无法正确解决。
#include <string.h>
#include <stdio.h>
char string1[] = "00-00-CA-FE-BA-BE";
char seps[] = "-";
char *token1 = NULL;
char *next_token1 = NULL;
int main( void )
{
unsigned char macAddress[6];
unsigned char ch;
int idx=0;
printf( "Tokens:\n" );
// Establish string and get the first token:
token1 = strtok_s( string1, seps, &next_token1);
while ((token1 != NULL))
{
sscanf_s(token1, "%02X", &macAddress[idx++], 1);
printf(" idx %d : %x\n", idx, macAddress[idx-1]);
token1 = strtok_s( NULL, seps, &next_token1);
}
}
如果有人能够找到问题或提出替代方案,我将感到非常高兴。
%X格式说明符用于整数,而不是字符。您需要将一个整数变量的地址传递给sscanf_s
您随后将其分配给字符的值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句