2017-01-04 49 views
0

我希望用戶爲int temp1和int temp2分配一個值。然而,編譯器說我需要初始化兩個變量之一(temp2)。爲什麼我需要在用戶給它賦值之前初始化這個變量?

爲什麼只是要求我初始化temp2而不是temp1?當我給temp2賦值時,程序會忽略用戶輸入的任何值。

是我的代碼馬虎,如果是這樣,有沒有辦法我可以解決這個問題?

(我已經包含了整個程序的情況下,它是相關的但是我收到的錯誤是在inputDetails()函數。)

#include <iostream> 
using namespace std; 

//Prototype 

void inputDetails(int* n1, int* n2); 
void outputDetails(int num1, int num2, int* pNum, int* n1, int* n2, int** ppNum); 

//Functions 

int main() 
{ 
int num1; 
//num1 pointer 
int* n1 = &num1; 

int num2; 
//num2 pointer 
int* n2 = &num2; 

//get pNum to point at num1 
int* pNum; 
pNum = new int; 
*pNum = num1; 

//pointer to pNum 
int** ppNum = &pNum; 

//call functions 
inputDetails(n1, n2); 
outputDetails(num1, num2, pNum, n1, n2, ppNum); 

//change pNum to point at num2 
delete pNum; 
pNum = new int; 
*pNum = num2; 

//call function again 
outputDetails(num1, num2, pNum, n1, n2, ppNum); 
delete pNum; 

system("PAUSE"); 
return 0; 
} 

void inputDetails(int* n1, int* n2) 
{ 
int temp1, temp2; 
cout << "Input two numbers" << endl; 
cin >> temp1, temp2; 
*n1 = temp1; 
*n2 = temp2; 
} 

void outputDetails(int num1, int num2, int* pNum, int* n1, int* n2, int** ppNum) 
{ 
cout << "The value of num1 is: " << num1 << endl; 
cout << "The address of num1 is: " << n1 << endl; 
cout << "The value of num2 is: " << num2 << endl; 
cout << "The address of num2 is: " << n2 << endl; 
cout << "The value of pNum is: " << pNum << endl; 
cout << "The dereferenced value of pNum is: " << *pNum << endl; 
cout << "The address of pNum is: " << ppNum << endl; 
} 
+0

聽你的編譯器。你的編譯器非常聰明:'* pNum = num1;'。在這一點上,'num1'是什麼初始化的?沒有。因此,編譯器告訴你。這可能沒有什麼壞處,但是,這項任務沒有任何意義,所以簡單地去除它。 –

+0

'* pNum = num1;'表示將'num1'的現有值複製到您剛剛分配的'new int'中。 (這是未定義的行爲,因爲你沒有初始化'num1')。它並不意味着「獲得pNum指向num1」 –

+0

new和delete通常只需要數組和結構體。對於單個整數和指針來說,聲明就足夠了;新的沒有相應的刪除將導致內存泄漏**小心**。 –

回答

4

爲什麼只要求我初始化temp2而不是temp1

以下沒有做什麼你認爲它(它在不經意間使用comma operator):

cin >> temp1, temp2; 

cin讀取兩個值,使用:

cin >> temp1 >> temp2; 
相關問題