2011-01-31 67 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类型的指针,那我们必须做类型转换。