繁体   English   中英

删除数组中的元素时出现分段错误(核心转储)错误

[英]Segmentation fault (core dumped) error while deletion of an element in an array

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

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

我创建了一个 function 来从数组中删除元素:

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;

}

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

这是 output 的样子:

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)

您忘记在删除scanf中扫描index

此外,此代码看起来不正确:

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

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

另一点 - 移动元素时,您可以使用像memmove()这样的大容量 function 而不是自己编写循环并冒犯错误的风险。 这在此线程中进行了解释。 您可以将循环替换为:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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