2012-11-26 66 views
0

我曾嘗試在C++中定義一個變量的數組大小,雖然我沒有完全理解動態內存的概念,但我使它工作。但是,在這種情況下,我不知道如何對數組「點」做同樣的事情。定義一個結構中的變量的數組大小

num=50; 
struct pos 
{ 
double x; 
}; 

struct pos point[num]; 

有沒有什麼明顯的我可以忽略?

+2

數組在標準C++中不能有動態大小。 – Pubby

+2

*有什麼明顯的我可以忽略嗎?*'std :: vector' – chris

回答

4

這些類型的數組大小必須是編譯時間常量,因此編譯器知道需要預留多少內存。

int count = 50; 
int arr[count] // error! 

static const int count = 50; 
int arr[count]; // OK! 

另一個選項是動態分配的內存,其中大小在運行時已知。

int count = 50; 
int* arr = new int[count]; 
delete [] arr; 

一般來講,你不希望是處理你自己的原始指針和內存分配,而應更喜歡:

#include <vector> 

int count = 50; 
std::vector<int> arr(count); 

這也將爲您有任何自定義類型工作只要它們能夠複製(提示:你的例子pos結構是可複製):

#include <vector> 

int count = 50; 
std::vector<pos> arr(count); 

arr[0].x = 1; 
// ... etc 
arr[49].x = 49; 

std::vector具有豐富的接口,並且所有的細節can be found here

+0

另一種選擇,如果不想'vector'的功能,就是使用'unique_ptr arr(new int [count];)'' – Praetorian

+0

是的,我很高興'unique_ptr'解決了'auto_ptr'沒有正確處理數組的問題。 – Chad

相關問題