【发布时间】: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