我有一个字符串(unsigned char),我想用十六进制字符填充它.
我的代码是
unsigned char str[STR_LEN] = {0};
for(i = 0;i<STR_LEN;i++) {
sprintf(str[i],"%x",rand()%16);
}
Run Code Online (Sandbox Code Playgroud)
当然,在运行这个时我会受到分裂
char-s not unsigned char-s 的数组str[i](它是类型unsigned char)作为第一个参数sprintf,但它需要类型char *(指针).这应该更好一点:
char str[STR_LEN + 1];
for(i = 0; i < STR_LEN; i++) {
sprintf(str + i, "%x", rand() % 16);
}
Run Code Online (Sandbox Code Playgroud)
第一个参数sprintf()应该是a char*,但是str[i]却是a char:这是分段错误的原因。编译器应该对此发出警告。gcc main.c,在没有指定高警告级别的情况下,发出以下内容:
警告:传递 sprintf 的参数 1 使指针来自整数而不进行强制转换
字符的十六进制表示可以是 1 或 2 个字符(9或AB例如)。对于格式设置,将精度设置为2并将填充字符设置为0。还需要添加一个字符作为终止 null并将循环str步骤设置为而不是(以防止覆盖先前的值):for21
unsigned char str[STR_LEN + 1] = {0};
int i;
for (i = 0; i < STR_LEN; i += 2)
{
sprintf(&str[i], "%02X", rand() % 16);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8748 次 |
| 最近记录: |