gpt4 book ai didi

c - 将 unsigned int 传递给函数是否会导致其丢失位?

转载 作者:行者123 更新时间:2023-11-30 19:25:39 25 4
gpt4 key购买 nike

我的问题与 here 非常相似只不过我正在和 C 一起工作。

我编写了一些代码来旋转无符号整数;即函数 bitRotate()(代码如下)。

当我直接输入我想要使用的文字而不是 printfscanf 时,该函数工作得非常好,例如bitRotate(0xabcdef00,8);在主函数中。

但是,当我将 x 作为参数传递(如以下代码中的 abcdef00 从用户处获取)时,x 会损坏为 ab000000。我多次检查、双重检查和调试我的代码,我很确定错误就在这部分,但我不明白为什么。

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define WIDTH sizeof(unsigned int)*CHAR_BIT

unsigned int bitRotate(unsigned int, char );

int main()
{

    unsigned int x;
    char n;
    while(1)
    {
        printf("Enter x: ");
        scanf("%x", &x);
        printf("Enter n: ");
        scanf("%d", &n);
        printf("%x\n", bitRotate(x,n));
    }

    return 0;
}

unsigned int bitRotate(unsigned int value, char n)
{

    char un = abs(n);
    unsigned int fallen = ~(0u);

    if(un == WIDTH)
        return value;
    else if (un < WIDTH)
    {

        if (n < 0)
        {
            fallen >>= (WIDTH - n);
            fallen = value & fallen;
            fallen <<= (WIDTH - n);
            value >>= n;
        }
        else
        {
            fallen <<= (WIDTH - n);
            fallen = value & fallen;
            fallen >>= (WIDTH - n);
            value <<= n;
        }
        value |= fallen;
        return value;

    }
    else
        return 0;

}

最佳答案

bitRotate 函数很好,你调用它的方式也很好。

真正的罪魁祸首在这里:

char n;
scanf("%d", &n); // <<<<<

您向 scanf 提供了错误的格式说明符,这会导致未定义的行为。您的编译器很可能会警告您这一点。

%d 格式说明符需要一个指向 int 的指针(通常需要 32 位),但您提供指向 char 的指针> 需要 8 位。因此,scanf 很可能会破坏与 n 地址相邻的内存。

你想要这个:

int n;
scanf("%d", &n);

关于c - 将 unsigned int 传递给函数是否会导致其丢失位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58542930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com