我想将一个字符串,比如“00-00-CA-FE-BA-BE”转换为 unsigned 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);
}
}
如果有人能找到问题或提出替代方案,我会很高兴。