如果我们有一个指针数组,即
struct node*ptr[];
如果我们想要将第一个索引(ptr[0]
)的值初始化为null,那么我们该怎么办呢?
答案 0 :(得分:2)
如果您希望能够初始化ptr[0]
,则必须为数组指定固定大小(例如struct node *ptr[1]
)或分配内存(struct node *ptr[] = new node *;
答案 1 :(得分:2)
您也可以这样做:
struct node* ptr [10] = { 0 };
将所有指针初始化为null。
答案 2 :(得分: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
答案 3 :(得分: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
}
答案 4 :(得分:1)
使用ptr[0] = NULL;
(假设您已正确声明ptr
,例如ptr[10]
)这就是您的要求吗?
答案 5 :(得分:0)
这是基于C
struct node*ptr[];
这意味着ptr可以保存节点的地址,它是一个节点类型指针的数组。就像
struct node *start = (struct node*)malloc(sizeof(struct node));
如你所知,数组大小是固定的,我们必须先使用数组大小,所以首先你要给出数组大小。
这里malloc(sizeof(struct node))
将返回void类型指针,我们必须进行类型转换。