gpt4 book ai didi

c - 函数中的空指针

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

我在这个程序中遇到了 void 指针的问题(很抱歉不得不提出整个程序...)。

#include "stdafx.h"
void Input_int(int& InputVar, int Min = -2147483647, int Max = 2147483647);
void Output_array(void* Array, unsigned int ElementNumber, unsigned int Type = 0);
//Type = 0 => int, 1 => bool.
bool* Convert_decimal_to_binary(int n);

void main()
{
int n;
bool* binary;
Input_int(n, -255, 255);
binary = Convert_decimal_to_binary(n);
printf("Binary's address: %d\n", binary);
Output_array(binary, 8, 1);
}

void Input_int(int& InputVar, int Min, int Max)
{
do {
printf("Please input an integer in range [%d;%d]: ", Min, Max);
scanf_s("%u", &InputVar);
if (InputVar > Max || InputVar < Min) printf("Your number is out of the range!\n");
} while (InputVar > Max || InputVar < Min);
}

bool* Convert_decimal_to_binary(int n)
{
static bool Array[8];
bool finishplus = false;
if (n < 0)
{
int i;
for (i = 7; i >= 0; i--)
{
if (n % 2 == 0) Array[i] = 0;
else {
if (!finishplus)
{
Array[i] = 0;
finishplus = true;
}
else
Array[i] = 1;
}
n = n / 2;
}
}
else {
for (int i = 0; i < 8; i++)
{
if (n % 2 == 0) Array[i] = 0;
else Array[i] = 1;
n = n / 2;
}
}
return Array;
}
void Output_array(void* Array, unsigned int ElementNumber, unsigned int Type)
{
if (Type == 0)
{
int* ArrayR;
ArrayR = (int*)Array;
for (unsigned int i = 0; i < ElementNumber; i++)
printf("Element %d got value: %d\n", i, ArrayR[i]);
}
else if (Type == 1)
{
bool* ArrayR;
printf("Array's address (in Output_array) before type explicited: %d\n", Array);
ArrayR = (bool*)Array;
printf("Array's address (in Output_array) after type explicited: %d", Array);
for (unsigned int i = 0; i < ElementNumber; i++)
printf("%d", i, ArrayR[i]);
printf("\n");
}
}

这里的主要问题在于这 3 行的输出:

printf("Binary's address: %d\n", binary);
printf("Array's address (in Output_array) before type explicited: %d\n", Array);
printf("Array's address (in Output_array) after type explicited: %d", Array);

为什么第三个输出与其他输出不同?

示例:

Binary's address: 11374900.
Array's address (in Output_array) before type explicited: 11374900.
Array's address (in Output_array) after type explicited: 1137490001234567.

在那里,"01234567" 总是出现。

提前致谢!

最佳答案

您忘记了最后一个 printf 上的 \n,因此它会附加您输出的下一个数字。指针本身没问题。

关于c - 函数中的空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20673013/

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