c - 如何在C中将值存储在动态数组中

标签 c dynamic-arrays

我正在尝试为动态数组中的元素赋值,但找不到解决方案。有很多视频展示了如果用户通过 scanf 输入值,它是如何工作的,但这里不是这种情况。我真的试图在这里和那里找到信息并自己解决它,所以我们将不胜感激任何帮助。 这是我的代码:

//Program co convert decimal number to binary and count zeros
int main()
{
    int decimalNum;
    int *binaryNum;
    int zeroCounter = 0;
    int i = 0;
    int sizeOfArray;
    int decimalNumCopied;


    printf("Please enter a number from 0 to 255: ");
    scanf("%d", &decimalNum);
    decimalNumCopied = decimalNum;

    while(decimalNum != 0)//checking number of bits;
    {
       decimalNum = decimalNum / 2;
       i++;
    }
    sizeOfArray = i;

    //Trying to allocate just enough memory 
    binaryNum = (int*)malloc(sizeOfArray * sizeof(int));


    while(decimalNumCopied != 0)
    {
        /*At next step I am trying to assign values to each element of the
        array and it doesn't work
        */
        binaryNum[i] = decimalNumCopied % 2;
        decimalNumCopied = decimalNumCopied / 2;
        i--;
    }

    for(i = 0; i <= sizeOfArray; i++)
    {
        printf("%d", binaryNum[i]);
        if(binaryNum[i]== 0){zeroCounter++;}
    }
    printf("\nThere are %d zeroes", zeroCounter);

    free(binaryNum);

    return 0;
}

最佳答案

您的第一个赋值超出了数组的范围。这会给您带来未定义的行为。

请记住,数组是从零开始索引的,因此如果 i 是数组的长度,则它不是有效索引(它比最后一个有效索引多了一个)。

关于c - 如何在C中将值存储在动态数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42763960/

相关文章:

c - 如何排除 "winsock2.h"?

c - 初始化返回变量时,读取缓冲区清零

c - C 中 __IO 和 static 关键字的用途是什么?

javascript - 在 JavaScript 中将数据构建到多维数组中

c++ - 自 C++20 以来,是否允许对分配的存储进行指针运算?

c++ - 将数组复制到另一个动态数组的问题

c - C中二维数组的内存分配

基于对话框的选项卡控件上的 C winapi 选项卡

c - 如何连接两个 Lua lua L_Buffer 对象?

C++ 矩阵到动态二维数组