为什么我的代码破坏了堆栈?我该如何解决?

时间:2019-10-27 10:57:52

标签: c stack

我需要制作一个可以更改小数的程序,该程序具有无符号字符范围。 我编写了代码,但是我使用的'number'变量类型却产生了问题。我认为我不应该因为这个问题的约束而将数字声明为整数类型变量...所以我应该如何解决呢?如何使我的程序不破坏“数字”变量的堆栈?

#include <stdio.h>
#define N_size 8
int main(void) {
    unsigned char number;
    int bin[N_size] = { 0 };
    printf("Input a decimal number of which range of unsigned char:"); 
    scanf("%d", &number);
    for (int i = 0; i < 8; i++){
        bin[N_size-1-i] = number % 2; number = number / 2;

    }
    for(int j=0;j<8;j++)
        printf("%d", bin[j]);

}

1 个答案:

答案 0 :(得分:0)

我认为堆栈已损坏,因为当数字变量具有无符号字符类型时,您使用了“%d”。您可以将其更改为“%ud”,但我认为这不会有所帮助。除此之外,您还可以使用联合数据结构。 Union为其所有内容共享内存。我前一段时间写了关于这个问题的程序:

#include <stdio.h>
#include <stdlib.h>
struct bits
{
       unsigned char bit0 : 1;
       unsigned char bit1 : 1;
       unsigned char bit2 : 1;
       unsigned char bit3 : 1;
       unsigned char bit4 : 1;
       unsigned char bit5 : 1;
       unsigned char bit6 : 1;
       unsigned char bit7 : 1;
};
union dectobin
{
    unsigned int value;
    struct bits bit;
};

int main()
{
    union dectobin w;
    int s;
    printf("Input a decimal number :");
    s=scanf("%ud",&(w.value));
    if(s!=1)
    {
        printf("Incorrect input");
        return 1;
    }
    printf("%d %d %d %d %d %d %d %d",(w.bit.bit7),(w.bit.bit6),(w.bit.bit5),(w.bit.bit4),(w.bit.bit3),(w.bit.bit2),(w.bit.bit1),(w.bit.bit0));
    return 0;
}