2011-01-31 66 views
1

,如果我們具有由具有的指針即數據結構++

struct node*ptr[]; 

,如果我們想通過空值,則我們如何能做到這一點,以初始化它的第一索引(ptr[0])的值的陣列?

+0

這是C,而不是C++。你的問題雖然指定了C++,但你已經將它標記爲C++。你在編寫C++還是C? – CashCow 2011-01-31 13:09:06

回答

1

使用ptr[0] = NULL;(假設您已正確聲明ptr,即類似ptr[10]的東西)那是你在問什麼?

2

如果你希望能夠初始化ptr[0]您必須指定您的陣列(struct node *ptr[1]例如)固定大小或分配內存(struct node *ptr[] = new node *;

+2

`struct node * ptr [] = new node *`實際編譯嗎?我相信你不能將變量`ptr`聲明爲'struct node * []`類型,因爲類型沒有完全定義(大小未知) – 2011-01-31 13:05:51

+0

@DavidRodríguez - dribeas:Right ...`struct node ** ptr =新節點*`應該更好:-) – Benoit 2011-01-31 13:09:13

2

你也可以做這樣的事情:

struct node* ptr [10] = { 0 }; 

它初始化所有的指針爲NULL。

2

struct node*ptr[];

並沒有真正聲明一個有效的數組,通常你需要指定一個大小或初始化的方式,使得編譯器可以在編譯時間處確定大小。另外,你不需要在C++中使用struct,這是C的倒退!

例如,有效的選項有:

node* ptr[10] = { 0 }; // declares an array of 10 pointers all NULL 

或者,你可以不大小初始化和編譯器計算出來..

node* ptr[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 10 node* pointers all NULL 
+0

實際上我想創建一個通用樹。它具有這種結構 – user596845 2011-01-31 13:20:57

2

如果你要使用大小固定的數組,使用std::array。如果使用,可以被調整大小的陣列,使用std::vector

#include <array> 
#include <vector> 

struct Node {}; 
typedef std::vector<Node*> DynamicNodeArray; 
typedef std::array<Node*, 10> StaticNodeArray; 

int main() 
{ 
    DynamicNodeArray dyn_array(10);  // initialize the array to size 10 
    dyn_array[0] = NULL;    // initialize the first element to NULL 

    StaticNodeArray static_array;  // declare a statically sized array 
    static_array[0] = NULL;    // initialize the first element to NULL 
} 
0

這是基於C

struct node*ptr[]; 

這意味着PTR可容納節點的地址,這是節點類型指針的陣列。就像

struct node *start = (struct node*)malloc(sizeof(struct node)); 

正如你所知數組的大小是固定的,我們必須給它的數組大小,因此首先你必須給出數組大小。

這裏malloc(sizeof(struct node))會返回void類型的指針,那我們必須做類型轉換。