0

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.

1
  • if(list->array[i] = NULL) --> if(list->array[i] == NULL) Commented Feb 2, 2014 at 21:35

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.