函数中的void指针

时间:2013-12-19 03:35:39

标签: c function void-pointers

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

#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的地址:11374900   类型说明之前的数组地址(在Output_array中):11374900   类型明确后的数组地址(在Output_array中):1137490001234567。

那里,"01234567"总是出现。

提前致谢!

1 个答案:

答案 0 :(得分:0)

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