Pergunta

I got a problem with void pointer in this program (I am sorry for having to bring up the whole bad program...).

#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");
    }
}

The main problem here is at the outputs of these 3 lines:

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);

Why the 3rd output is different from the others?

Example:

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

there, "01234567" always appear.

Thanks in advance!

Foi útil?

Solução

You forgot the \n on the last printf so it's appending the next number you output. The pointer itself is fine.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top