Reputation: 197
My problem requires conversion of fixed Array size to dynamic memory allocation. I have tried all sorts of calloc, malloc and relloc statements but nothing seemed to work. I guess even a void *data pointer was useless.
Please convert this code for dynamic memory so that I can resize the array later. Also to add I am working with linked list so this array is a Node pointer.
Node *lists[100] //this does my job
lists[listNo] = NULL;
if I want to use malloc:
Node *lists = (Node) malloc(100*sizeof(Node));
lists[listNo] = NULL; // gives me error when I use malloc or calloc and the error is assigning Node from void*
Upvotes: 0
Views: 438
Reputation: 4069
Based on your assertion that:
Node *lists[100]
...does the job, then that's an array of 100 pointers (to type Node
). The usual variable-length version of that is:
Node **lists; /* points to first pointer in dynamic array */
int lists_size; /* you need a variable to hold the size */
If the array is very large, use size_t
from <stdlib.h>
instead of int, but int is easier to use with small arrays and index variables. Allocate that with:
lists_size = 100; /* replace 100 with a computed size */
lists = (Node**)calloc(lists_size, sizeof (Node*));
Use lists_size
in place of 100 in your code and everything else will work the same. Use of calloc() instead of malloc() will clear the allocated memory to binary zeroes, eliminating the need for loop to store NULL pointers on every actual implementation. (Technically, the C standard doesn't require NULL to be zero, or at least didn't the last time I looked, but a few megatons of Unix plus Windows code requires this.)
Upvotes: 3
Reputation: 22134
The problem is that lists should be defined as a pointer to an array of pointers when using malloc.
Node **lists = malloc(100*sizeof(Node*));
lists[listNo] = NULL;
Upvotes: 5