2

I want to have dynamic size of array of pointers, how can I do it with malloc? without malloc it looks like this:

typedef struct Nodes {
    UINT_64 Datasequence; 
    UINT_32 Data; 
    struct Nodes *next;
} Node;

Node *head_ri_interface[2][50];

which will give me an array of [2][50] of null pointers.

I have tried this:

void NULLPointerArrayInit(int MAX_LIST_HEAD) {
    int i = 0;

    for (i = 0; i < 2; i++) {
        head_ri_interface[i] = (Node *)malloc(sizeof(Node *) *  MAX_LIST_HEAD);
    }
}

but I see that I get that the struct I am pointing at are not NULL. what am I doing wrong?

chqrlie
  • 131,814
  • 10
  • 121
  • 189
Omer Anisfeld
  • 1,236
  • 12
  • 28

1 Answers1

1
void ** 2Darray = malloc(2*sizeof(void*));

int i;
for(i = 0; i < 2; i++){
    2Darray[i] = malloc(MAX_LIST_HEAD*sizeof(void*));
    memset(2Darray[i], 0, MAX_LIST_HEAD*sizeof(void*));
}

So what i did here: I allocated memory for 2 pointer types. Than pointed each of this two pointers to MAX_LIST_HEAD times size of pointer type memory (you can assume it's an array of pointers size - MAX_LIST_HEAD); After that I wrote zeros to all pointers, this means they are pointing to NULL.

(If pointer is pointing to 0 it means it is pointing to NULL. But when pointer is pointing to NULL it does not always mean it is pointing to 0)

  • You should consider using `calloc` or initializing the array of pointers with a loop. – chqrlie Jul 29 '18 at 12:43
  • @chqrlie Yes I forgot, In `calloc` it would have been better visible what I did here. Thanks. But I think it works either. – Data Chanturia Jul 29 '18 at 12:45
  • The type `void**` is inconsistent with the allocation method. The OP wants to allocate a pseudo-2D array of `Node*`. – chqrlie Jul 29 '18 at 12:52
  • 1
    thank's i used this answer just with this minor change of alyways first dimension is size of 2 meands : ~ Node * head_ri_interface[2] ; void NULLPointerArrayInit(int MAX_LIST_HEAD){ int i = 0 ; for(i = 0; i < 2; i++) { head_ri_interface[i] = (Node *) CALLOC (MAX_LIST_HEAD, sizeof(ACL_Node *)); } } ~ – Omer Anisfeld Jul 29 '18 at 14:08