2013-12-19 175 views
-1

我在這個程序中遇到了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.

那裏,""總是出現。

提前致謝!

+1

請發佈[最小測試用例](http://sscce.org)。 –

+0

如果註釋掉以下內容會發生什麼情況:ArrayR =(bool *)Array; – tier1

+0

Tagged C++ - 爲什麼'printf'等?當你失去類型安全時,也要避免使用'void'指針。 –

回答

0

您忘記了最後printf上的\n,因此它會附加您輸出的下一個數字。指針本身很好。

+0

非常感謝!對不起,很煩人.. – ntvy95

+1

@ ntvy95,根本不煩人。很容易錯過最簡單的事情。 –

+0

查看自己的程序也很容易,並注意到非常明顯的...程序明確地打印這些數字;他們必須出現在輸出*某處*。 –