Вопрос

I'm working on an assignment and I have to write a function that takes in a dynamically allocated array of strings and an index, and removes the element at that index. Using a sample main function provided to test the code, it crashes at the first call of the function, and I have no idea why. Here's my code.

int removeElement(ArrayList *list, int index)
{
    int i;

if(list != NULL && index < list->size)
{
    for(i = index; i < list->size - 1; i++)
    {
        free(list->array[i]);
        list->array[i] = malloc(sizeof(char) * (strlen(list->array[i + 1]) + 1));
        if(list->array[i] = NULL)
        {
            printf("Can't allocate memory. Returning 0.\n");
            return 0;
        }

        strcpy(list->array[i], list->array[i + 1]);
    }

    free(list->array[i]);
    list->array[i] = NULL;
    list->size--;
    return 1;
}

return 0;
};

I think it might be because the first string ("List of names") is larger than the second ("Sean"). But I'm still confused regarding to how it works.

Это было полезно?

Решение

This is not a direct answer to your question, but you might as well just copy pointers instead of all these mallocs and strcpys:

int i;
if (list != NULL && index < list->size)
{
    free(list->array[index]);
    for (i=index; i<list->size-1; i++)
        list->array[i] = list->array[i+1];
    list->size--;
    return 1;
}

Or if you don't mind the order of the strings, then even better:

if (list != NULL && index < list->size)
{
    free(list->array[index]);
    if (index < list->size-1)
        list->array[index] = list->array[list->size-1];
    list->size--;
    return 1;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top