我在这个程序中遇到了void pointer的问题(我很抱歉不得不提起整个坏的程序...)。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);
为什么第3个输出是从别人有什么不同?
实施例:
二进制地址:11374900.
阵列的地址(在Output_array)类型explicited之前:类型后11374900.
阵列的地址(在Output_array)explicited:11374900.
那里,""
总是出现。
提前致谢!
请发布[最小测试用例](http://sscce.org)。 –
如果注释掉以下内容会发生什么情况:ArrayR =(bool *)Array; – tier1
Tagged C++ - 为什么'printf'等?当你失去类型安全时,也要避免使用'void'指针。 –