0

I can init all of memory for node parameters, now I just want initialize one of the struct parameters (node-> nb ), but have error

My code

#define v 10

typedef struct node_type{
    int id;
    int nb[v];
    bool link_capacity;
}node_t;

int main()
{
    int i,j;
    
    node_t *node;
    node = (node_t *) malloc(v*sizeof(node_t));
    memset(node, 0, v*sizeof(node_t));
    
    node[0].nb[0]=1;
    node[1].nb[0]=2;
    node[0].id=1;
    node[1].id=2;

    printf("%d %d %d %d\n",node[0].nb[0],node[1].nb[0],node[0].id,node[1].id);

    memset(node->nb, 0, v*sizeof(node_t));
    
    printf("%d %d %d %d\n",node[0].nb[0],node[1].nb[0],node[0].id,node[1].id);
    return 0;
}
Ans: 
1 2 1 2
0 0 1 0

But I hope that Ans:
1 2 1 2
0 0 1 2

How to modify?

1 Answers1

0

Why do you zero 10 times the size of a node_t with

memset(node->nb, 0, v*sizeof(node_t)); ?

To zero just the nb array, use

memset(node[0].nb, 0, sizeof(node[0].nb));

You need to loop over node[i].nb if you want all such arrays cleared.

Jens
  • 69,818
  • 15
  • 125
  • 179
  • Thank you for your response. Then node[i] that can't it be cleared directly? must use loop? – guanting.lai Dec 22 '21 at 13:21
  • @guanting.lai Yes you need a loop, since the `nb[i]` arrays are not next to each other in memory. `for(int i = 0; i < v; ++i) memset(node[i].nb, 0, sizeof(node[0].nb));` – Jens Dec 22 '21 at 13:28