[英]Data structure using c++
if we are having are having an array of pointer ie 如果我们有一个指针数组,即
struct node*ptr[];
and if we want to initialize its value of first index ( ptr[0]
) by null then how can we do that? 如果我们想将其第一个索引( ptr[0]
)的值初始化为null,那么我们该怎么做呢?
如果要初始化ptr[0]
,则必须为数组指定固定大小(例如struct node *ptr[1]
)或分配内存( struct node *ptr[] = new node *;
You can also do something like this: 您还可以执行以下操作:
struct node* ptr [10] = { 0 };
which initializes all pointers to null. 这会将所有指针初始化为null。
struct node*ptr[];
does not really declare a valid array, typically you need to specify a size or initialize in such a way that the compiler can determine the size at compile time . 并没有真正声明有效的数组,通常您需要指定大小或以编译器可以在编译时确定大小的方式进行初始化。 Also, you don't need the struct
in C++, it's a throwback to C! 另外,您不需要C ++中的struct
,这是对C的回溯!
for example, valid options are: 例如,有效的选项是:
node* ptr[10] = { 0 }; // declares an array of 10 pointers all NULL
or, you can initialize without the size and the compiler figures it out.. 或者,您可以在没有大小的情况下进行初始化,然后编译器将其弄清楚。
node* ptr[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 10 node* pointers all NULL
If you are trying to use a statically sized array, use std::array
. 如果您尝试使用静态大小的数组,请使用std::array
。 If you using an array that can be resized, use std::vector
: 如果使用的数组可以调整大小,请使用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
}
Use ptr[0] = NULL;
使用ptr[0] = NULL;
(assuming you have declared ptr
correctly ie something like ptr[10]
) Is that what you are asking? (假设您正确声明了ptr
,例如ptr[10]
类的东西),那是您要问的吗?
This is based on C 这是基于C
struct node*ptr[];
This means ptr can hold address of node, it is a array of node type pointer. 这意味着ptr可以保存节点的地址,它是节点类型指针的数组。 just like 就像
struct node *start = (struct node*)malloc(sizeof(struct node));
As you know array size is fixed, we have to give array size before it's use, so first of all you have to give array size. 如您所知,数组大小是固定的,我们必须在使用数组大小之前先确定它的大小,因此首先必须给出数组大小。
Here malloc(sizeof(struct node))
will return void type pointer, that by we have to do type casting. 这里malloc(sizeof(struct node))
将返回void类型指针,这是我们必须进行类型转换的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.