gpt4 book ai didi

c - 列表 ADT - 如何释放结构指针及其成员?

转载 作者:行者123 更新时间:2023-11-30 15:01:51 24 4
gpt4 key购买 nike

下面是一个列表 ADT,

typedef struct List{
void **array;

/* Following members for Housekeeping - Array enhancement*/
int lastItemPosition;
int size;
}List;
#define INITIAL_LIST_SIZE 50
<小时/>

createList 操作尝试 free(*(list->array)) ,期望仅释放 void* 的数组,但不释放指向每个 void* 的对象,因为 listPointer 获取 list

的浅拷贝
List *createList(List *list, Op opType){

List *listPointer = (List *)malloc(sizeof(List));
void *accumulator = NULL;
if(opType == CREATE_NEW_LIST){

accumulator = malloc(INITIAL_LIST_SIZE*sizeof(void*));
listPointer->array = &accumulator;

/* Is it safe to initialise zero to element of array of void* pointers? */
listPointer->array = memset(listPointer->array, 0, INITIAL_LIST_SIZE*sizeof(void *));

listPointer->lastItemPosition = -1;
listPointer->size = INITIAL_LIST_SIZE;
}else if(opType == DOUBLE_THE_LIST){

accumulator = malloc(2*(list->size)*sizeof(void *));
listPointer->array = &accumulator;

/* Performing shallow copy, Is deep copy required? */
listPointer->array = memcpy(listPointer->array, list->array, list->size*sizeof(void*));

listPointer->lastItemPosition = list->lastItemPosition;;
listPointer->size = 2*(list->size);

free(*(list->array)); // How to free list pointer and its members?

}else if(opType == HALF_THE_LIST){

accumulator = malloc(((list->size)/2)*sizeof(void *));
listPointer->array = &accumulator;

/* Performing shallow copy, Is deep copy required? */
listPointer->array = memcpy(listPointer->array, list->array, (list->size/2)*sizeof(void *));
listPointer->lastItemPosition = list->lastItemPosition;
listPointer->size = (list->size)/2;

free(*(list->array)); // How to free list pointer and its members?
}

return listPointer;

}
<小时/>

执行以下列表操作List

void insertItem(List *, void *newItem);
void deleteItem(List *, int listIndex);

用户访问,

/* main.c */

#include"list.h"

int main(void){
List *arrayList = createList((List *)NULL, CREATE_NEW_LIST);


if (arrayList == (List *)NULL){
fprintf(stderr, "Unable to createList() \n");
exit(1); //Nothing else to do without arrayList
}

/* Objects should be on heap */
int *object = malloc(sizeof(int));

*object = 650;


insertItem(arrayList, object);
}
<小时/>

问题:

您能否澄清一下,free(*(list->array)) 在我的代码中做了什么?

最佳答案

以下代码片段应该可以完成这项工作:

else if(opType == DOUBLE_THE_LIST){

listPointer->array = realloc(listPointer->array, 2*(list->size)*sizeof(void *));

listPointer->lastItemPosition = list->lastItemPosition;;
listPointer->size = 2*(list->size);

// do not free any more: free(*(list->array)); // How to free list pointer and its members?
}

关于c - 列表 ADT - 如何释放结构指针及其成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41229244/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com