0
votes

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*
2
Are you perhaps using a C++ compiler for C code? Try #ifdef __cplusplus #error wrong compiler #endifpmg
I am using C compiler onlyAbhishek Singh
Could you show the code where you sue malloc and you get an error ? Do you get a compilation error or an error when executing the code ?chmike
You cannot assign a pointer to an object (Node_var = pointer); if Node_var is a pointer, assigning it a value of type void* is ok in Cpmg
You are using a c++ compiler... in c void * is converted to any poitner type...Iharob Al Asimi

2 Answers

5
votes

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;
3
votes

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