【问题标题】:Segmentation fault (core dumped) error while deletion of an element in an array删除数组中的元素时出现分段错误(核心转储)错误
【发布时间】:2022-01-14 15:41:45
【问题描述】:

我写了一个动态创建数组的基本代码:

void makeArray(struct Array * a)
{
    int capacity, need;
    printf("Enter the capacity of the array you want: ");
    scanf("%d", &capacity);
    printf("Enter the capacity you are going to use: ");
    scanf("%d", &need);
    a -> used_size = need;
    a -> total_size = capacity;
    a -> ptr = (int*)malloc (capacity * sizeof(int));
}

我创建了一个从数组中删除元素的函数:

void indDeletion(struct Array * a)
{
    int index;
    printf("Enter the position you would like to delete the number in: ");
    for(int i = index; a -> used_size - 1; i++)
    {
        a -> ptr[i] = a -> ptr[i+1];
    }
    a -> used_size -= 1;

}

当我插入元素时代码工作正常,但是当我调用删除函数时它显示分段错误(核心转储)。

这是输出的样子:

Enter the capacity of the array you want: 100
Enter the capacity you are going to use: 4
Enter element 0: 1
Enter element 1: 2
Enter element 2: 3
Enter element 3: 4
Element 0: 1
Element 1: 2
Element 2: 3
Element 3: 4
Enter the position you would like to insert the number in: 3
Enter the number: 123
Insertion was successful
Element 0: 1
Element 1: 2
Element 2: 3
Element 3: 123
Element 4: 4
Segmentation fault (core dumped)

【问题讨论】:

  • 我添加它是为了减少删除元素后使用的大小
  • for(int i = index; a -> used_size - 1; i++) - 仔细检查循环条件。
  • 天哪,我太笨了,非常感谢你

标签: arrays c data-structures


【解决方案1】:

您忘记在删除功能中为index 输入scanf

另外,这段代码看起来不正确:

    for(int i = index; a -> used_size - 1; i++)
    {
        a -> ptr[i] = a -> ptr[i+1];
    }

条件a -> used_size -1 永远不会改变,因为您永远不会在循环中修改a -> used_size。所以要么循环永远不会运行,要么永远运行。

另外一点 - 移动元素时,您可以使用像 memmove() 这样的批量函数,而不是自己编写循环并冒犯错误的风险。这在this thread 中有解释。您可以将循环替换为:

memmove(&(a->ptr)[i], &(a->ptr)[i+1], (a->used_size - 1 - index)*sizeof(int));

【讨论】:

    猜你喜欢
    • 2021-06-15
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多