用于异或运算的C程序,由scanf输入的运算符

问题描述 投票:0回答:1

我编写了一个小程序来运行按位XOR操作。这些值应插入命令行中:

#include <stdio.h>

int main()
{
    unsigned char x = 0, y= 0;

    printf("This program performs a Bitwise XOR operation of two chars\n");
    printf("Enter a value for the first variable: ");
    scanf("%i",&x);

    printf("Enter a value for the second variable: ");
    scanf("%i",&y);
    printf("1. Value = %i\n2. Value = %i\n",x,y);

    y ^= x;

    printf("Result XOR-Operation = %i", y);
    printf("\nResult in hex: 0x%i", y);

    return 0;
}

当我运行程序时,它的第一个值返回0 ...

命令行输出:

1 This program performs a Bitwise XOR operation of two chars
2 Enter a value for the first variable: 10
3 Enter a value for the second variable: 5
4 1. Value = 0
5 2. Value = 5
6 Result XOR-Operation = 5
7 Result in hex: 0x5

我正在使用gcc编译器,并在Windows命令行中运行它。我可能需要使用指针吗?找不到与此主题相关的内容...

提前感谢!

c scanf bitwise-xor
1个回答
1
投票

%i格式说明符期望使用int *,但您正在传递给它unsigned char *。由于后者指向较小的数据类型,因此scanf将尝试越过其要写入的变量的边界进行写入。这导致undefined behavior

您想使用hh修饰符告诉scanf期望正确的指针类型。

scanf("%hhi",&x);
...
scanf("%hhi",&y);
© www.soinside.com 2019 - 2024. All rights reserved.