gpt4 book ai didi

c - 扩展动态分配的指针数组

转载 作者:行者123 更新时间:2023-11-30 15:39:16 26 4
gpt4 key购买 nike

这真是太痛苦了。我试图动态分配一个数组并使用 realloc、calloc 和 malloc,但这三个方法都没有给我带来任何结果。看起来我已经成功扩展了它,但我无法正确复制它。扩展函数中的所有内容都很好,但在我调用该函数后,它就变得毫无用处。

typedef struct ArrayList
{
// We will store an array of strings (i.e., an array of char arrays)
char **array;

// Size of list (i.e., number of elements that have been added to the array)
int size;

// Length of the array (i.e., the array's current maximum capacity)
int capacity;

} ArrayList;

ArrayList *expandArrayList(ArrayList *list, int length){
struct ArrayList *temp=realloc(list, length);
if (length<list->capacity){
return NULL;
free(temp);
}
if (temp)
list=temp;
else{
free(temp);
return NULL;
}
list->capacity=length;
printf("-> Expanded ArrayList to size %d.\n", length);
return list;
}

最佳答案

我猜您实际上想扩展 ArrayListarray容量。那么函数应该是这样的:

#include <errno.h>
ArrayList *expandArrayList(ArrayList *list, int new_capacity){
if (list->capacity >= new_capacity) {
return list; // If a smaller capacity is passed in, do nothing.
}

char **tmp = realloc(list->array, new_capacity * sizeof(char*));
if (tmp) {
list->capacity = new_capacity;
list->array = tmp; // On success, set 'array' field of 'list' to tmp.
} else {
if (errno == ENOMEM) {
fprintf(stderr, "Error: not enough memory.\n"); // On failure, report the error and exit.
exit(1);
}
}

return list;
}

我还没有测试过代码,但希望这对你有帮助。

关于c - 扩展动态分配的指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21518119/

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