[英]Reversing input every two characters
I've been trying to make a program that takes an address and reverses it for every two characters. 我一直在尝试制作一个程序,该程序需要一个地址,并每两个字符反转一次。 An example input would be "0xefba5896" and ideally it's output would be "\\x96\\x58\\xba\\xef".
输入示例为“ 0xefba5896”,理想情况下,其输出为“ \\ x96 \\ x58 \\ xba \\ xef”。 The trouble I'm getting is that the first few bytes work, but the last one doesn't print.
我遇到的麻烦是前几个字节有效,但最后一个不打印。 My code is below:
我的代码如下:
int i;
char *add = argv[1];
char rev[8];
char xa[2];
strncpy(rev, &add[2], strlen(add));
for (i = strlen(rev) - 2; i > -2; i-=2) {
if (i == 0) {
strncpy(xa, &rev[0], 2);
} else {
strncpy(xa, &rev[i], 2);
xa[2] = '\0';
}
printf("\\x%s", xa);
}
If I input "0xefba5896" my output is: 如果输入“ 0xefba5896”,则输出为:
\x96\x58\xba\x
If the answer is obvious to someone, please forgive me. 如果答案对某人显而易见,请原谅我。 I've been learning C for only about a week.
我已经学习C大约一个星期了。 Any help would be immensely appreciated!
任何帮助将不胜感激!
It makes no sense to pass strlen(add)
as the limiting factor to strncpy
, if add
is longer than 10, you will still overflow rev
! 将
strlen(add)
作为限制因素传递给strncpy
没有意义,如果add
大于10,您仍然会溢出rev
!
You have to pass the size of the destination , not the size of the source. 您必须传递目标的大小,而不是源的大小。 So the correct call is
所以正确的电话是
strncpy(rev, add+2, sizeof rev);
rev[sizeof(rev) - 1] = 0;
Also note that strncpy
does not necessarily write the '\\0'
-terminating byte if the destination is not long enough, so you should always set the '\\0'
-terminating byte yourself. 还要注意,如果目标的时间不够长,
strncpy
不一定会写入'\\0'
终止字节,因此您应始终自行设置'\\0'
终止字节。
Also note that xa[2] = '\\0';
还要注意
xa[2] = '\\0';
overflows xa
, because the size of xa
is 2, so the maximal index is 1
. 溢出
xa
,因为大小xa
为2,最大索引是1
。 If you want to store 2 characters in xa
, then xa
needs to be of at least dimension 3. Same goes for rev
. 如果要在
xa
存储2个字符,则xa
尺寸至少应为rev
。 So You have to declare xa
as this: 因此,您必须将
xa
声明为:
char rev[9];
char xa[3];
So when you use strncpy
, you should use it like this: 因此,当您使用
strncpy
,应该这样使用它:
char dest[8];
strncpy(dest, src, sizeof dest);
dest[sizeof(dest) - 1] = 0;
So you can rewrite your program like this: 因此,您可以像这样重写程序:
int main(int argc, char **argv)
{
if(argc != 2)
{
fprintf(stderr, "usage: %s address\n", argv[0]);
return 1;
}
size_t len;
char *add = argv[1];
char rev[9];
char xa[3];
strncpy(rev, add + 2, sizeof rev);
rev[sizeof(rev) - 1] = 0;
len = strlen(rev);
if(len & 1)
{
fprintf(stderr, "Invalid length of address, needs an even number of characters\n");
return 1;
}
for(size_t i = len - 2; i >= 0; i -= 2)
{
strncpy(xa, rev + i, sizeof xa);
xa[sizeof(xa) - 1] = 0;
printf("\\x%s", xa);
fflush(stdout);
}
putchar('\n');
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.