【问题标题】:Expanding a Dynamically Allocated Pointer Array扩展动态分配的指针数组
【发布时间】:2014-02-26 09:26:55
【问题描述】:

这太痛苦了。我正在尝试动态分配一个数组并使用 realloc、calloc 和 malloc,但是这三个都没有让我做任何事情。好像我已经成功扩展了它,但是我无法正确复制它。 expand 函数中的一切都很好,但是在我调用该函数之后它就变得没用了。

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;
}

【问题讨论】:

    标签: c arrays pointers dynamic expand


    【解决方案1】:

    我猜你实际上想在ArrayList 中扩展arraycapacity。 那么函数应该是这样的:

    #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;  
    }
    

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

    【讨论】:

    • 如果可以,你能告诉我我做错了什么吗?现在一切正常。
    • 一些主要问题: 1. 在您的原始代码中,您试图重新分配 ArrayList,但您想要重新分配的真正数据结构是保存指针的 char** 数组。 2. 不能只将capacity 传递给realloc,因为char* 在内存中占用4 个字节,您应该将capacitysizeof(char *) 相乘。
    【解决方案2】:

    ArrayList 有一个固定的大小:一个指针 + 两个整数。在指向 ArrayList 的指针上重新分配内存没有意义。您想要重新分配的要么是列表指针指向的内存,要么是数组指针指向的内存,或者两者兼而有之。 在 return 之后放置的 free() 将永远不会运行,整个代码让我想知道您在更广泛的上下文中试图实现什么。

    【讨论】:

      猜你喜欢
      • 2017-06-20
      • 2018-06-23
      • 1970-01-01
      • 1970-01-01
      • 2012-09-16
      • 2013-05-26
      • 2020-05-17
      • 1970-01-01
      相关资源
      最近更新 更多