简体   繁体   中英

Dynamic Memory allocation C

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*

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;

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM