Question

This has been such a pain. I'm trying to dynamically allocate an array and used realloc, calloc, and malloc but neither of the three has lead me to anything. It seems like I have successfully expanded it, but I have not been able to copy it correctly. Everything within the expand function is okay but after I call the function it becomes useless.

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;
}
Was it helpful?

Solution

I guess you would like to expand the capacity of the array in ArrayList actually. Then the function should be like:

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

I have not tested the code, but I hope this would help you.

OTHER TIPS

ArrayList has a fixed size: one pointer + two ints. Reallocating memory on a pointer to an ArrayList makes no sense. It's either the memory pointed to by the list pointer, or the memory pointed to by the array pointers, or both, that you want to reallocate. The free() put after a return will never be run, and the whole code makes me wonder what you are trying to achieve in a broader context.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top