简体   繁体   English

动态内存分配C

[英]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. 我尝试了各种calloc,malloc和relloc语句,但似乎没有任何效果。 I guess even a void *data pointer was useless. 我想即使是无效的* data指针也没有用。

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指针。

Node *lists[100]  //this does my job 
lists[listNo] = NULL; 

if I want to use malloc: 如果我想使用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. 问题在于,使用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 ). ...完成这项工作,那么就是一个由100个指针组成的数组(键入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. 如果数组非常大,请使用<stdlib.h> size_t代替int,但使用小数组和索引变量更容易使用int。 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. 在代码中使用lists_size代替100,其他所有内容都将保持相同。 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. 使用calloc()而不是malloc()会将分配的内存清除为二进制零,从而消除了在每个实际实现上循环存储NULL指针的需要。 (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.) (从技术上讲,C标准不需要NULL为零,或者至少我上次没有要求NULL,但是需要几百万的Unix和Windows代码。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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