c - 十进制到二进制函数中的段错误

标签 c function

我尝试编写一个函数,将十进制数转换为 32 位二进制数组。这是我的代码:

void show_bits(int x) {
    int array[32];
    int n;

    while (x >= 0) {

     if (x%2 == 0) {
         array[n] = 0;

     }
     else {
         array[n] = 1;
     }
    x = x/2;
    n++;
    }

    for (int i; i<32; i++) {
     printf("%d ", array[i]);
    }
}

我不太确定我做错了什么,非常感谢任何帮助。

最佳答案

void show_bits(int x) {
    int array[32];
    int n;

    while (x >= 0) {
     if (x%2 == 0) {
         array[n] = 0;  /* ERROR HERE: n isn't set */
     }

n 使用未初始化 = 未定义的行为。

关于c - 十进制到二进制函数中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59815836/

相关文章:

php - 用于显示 mysql 版本 5.0.45 的 mysql 数据库中用户定义函数的代码的 Mysql 查询是什么?

c - 无符号指针的非法隐式转换

c - 用户定义的销毁(免费)功能

javascript - jQuery 文档就绪 - 函数调用 : sequential or asynch?

bash - 可以在 bash if 语句中使用调用 "test"的函数吗?

python - 获取数字列表并返回平均值

angular - 这个函数的签名是什么意思?

c - inet_ntop 的第二个参数的正确类型/格式是什么?

c - 为什么我的冒泡排序程序的输出每次运行时都会改变?

c - 错误 : invalid operands to binary expression