简体   繁体   English

从c中的字符串数组中删除字符串

[英]Removing a string from an array of strings in c

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"). 我认为可能是因为第一个字符串(“名称列表”)大于第二个字符串(“ 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 malloc s and strcpy s: 这不是您问题的直接答案,但您最好只复制指针,而不要复制所有这些mallocstrcpy

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM