2011-09-02 46 views
2

我想要2,4,6顯示...而我認爲地址數字顯示?C++:我想要2,4,6顯示...而我認爲地址數字顯示?

我需要做些什麼來糾正,爲什麼? 感謝

(目的...演示改變陣列的空間,仍然保持了數組的基本能力)

int *line; 

    line = new int; 
    line[0] = 2; 
    line = new int; 
    line[1] = 4; 
    line = new int; 
    line[2] = 6; 
    line = new int; 
    printf("%d %d %d", line[0], line[1], line[2]); 
+4

嗯,你確定破壞堆好..更不用說四個內存泄漏試圖顯示三個數字... – Blindy

+0

http://augustcouncil.com/~tgibson/tutorial/arr.html – Rook

+0

如果你想要「改變陣列空間並保持基礎」(我想你的意思是「初始片段」?),你不會繞過將舊陣列複製到新分配的區域。順便說一下,有一個叫做std :: vector 的類,它正是爲你做的;-) –

回答

7

試試這個:

int *line; 

line = new int[3]; 
line[0] = 2; 
line[1] = 4; 
line[2] = 6; 
printf("%d %d %d", line[0], line[1], line[2]); 
delete[] line; 

點要注意:

line = new int[3]; // here you are supposed to specify the size of your new array 
... 
delete[] line; // whenever you use new sometype[somevalue]; 
       // you must call delete[] later on to free the allocated resources. 

也看看這個問題,在這樣:

delete vs delete[] operators in C++

3

你在每一個new int覆蓋指針line。而你正在從它之前泄漏的記憶。

此外,由於您只分配一個int,因此只定義了line[0]。 訪問line[1]line[2]未定義。

+0

+1來解釋原因 –

1

line = new int替換東西line分以新分配的尺寸爲int的堆棧。

2

您聲明int*並分配intnew。此時line包含指向int的地址。

訪問line[1]line[2]是等待發生的崩潰,因爲這些位置包含垃圾。你從來沒有在這些地方分配內存。

2

在我後面重複:「這不是Java,我不會使用new,沒有很好的理由。」

對於三個整數數組,你只是想是這樣的:

int line[] = {2, 4, 6}; 

要打印出來,你通常要使用的std::cout而不是printf

std::cout << line[0] << " " << line[1] << " " << line[2]; 

注意,特別是,沒有理由使用new完成這項任務。