Reputation: 29
if we are having are having an array of pointer i.e.
struct node*ptr[];
and if we want to initialize its value of first index (ptr[0]
) by null then how can we do that?
Upvotes: 1
Views: 255
Reputation: 147
This is based on C
struct node*ptr[];
This means ptr can hold address of node, it is a array of node type pointer. 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.
Upvotes: 0
Reputation: 15872
If you are trying to use a statically sized array, use std::array
. If you using an array that can be resized, use 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
}
Upvotes: 2
Reputation: 33655
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!
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
Upvotes: 2
Reputation: 1187
You can also do something like this:
struct node* ptr [10] = { 0 };
which initializes all pointers to null.
Upvotes: 2
Reputation: 79165
If you want to be able to initialize ptr[0]
you must either specify a fixed size for your array (struct node *ptr[1]
for example) or allocate memory (struct node *ptr[] = new node *;
Upvotes: 2
Reputation: 11232
Use ptr[0] = NULL;
(assuming you have declared ptr
correctly i.e. something like ptr[10]
) Is that what you are asking?
Upvotes: 1