我正在尝试为动态数组中的元素赋值,但找不到解决方案。有很多视频展示了如果用户通过 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/