【发布时间】:2018-06-29 15:03:43
【问题描述】:
我在 C 工作
我有一个名为 Entity 的结构,并创建了该结构的动态数组。然后我尝试从数组中删除一个元素,但我没有得到我想要的行为。
这是我正在使用的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Entity
{
int x, y;
int velX, velY;
}Entity;
int remove_element(Entity** array, int sizeOfArray, int indexToRemove)
{
int i;
printf("Beginning processing. Array is currently: ");
for (i = 0; i < sizeOfArray; ++i)
printf("%d ", (*array)[i].x);
printf("\n");
Entity* temp = malloc((sizeOfArray - 1) * sizeof(Entity)); // allocate an array with a size 1 less than the current one
memmove(
temp,
*array,
(indexToRemove+1)*sizeof(Entity)); // copy everything BEFORE the index
memmove(
temp+indexToRemove,
(*array)+(indexToRemove+1),
(sizeOfArray - indexToRemove)*sizeof(Entity)); // copy everything AFTER the index
printf("Processing done. Array is currently: ");
for (i = 0; i < sizeOfArray - 1; ++i)
printf("%d ", (temp)[i].x);
printf("\n");
free (*array);
*array = temp;
return 0;
}
int main()
{
int i;
int howMany = 20;
Entity* test = malloc(howMany * sizeof(Entity*));
for (i = 0; i < howMany; ++i)
(test[i].x) = i;
remove_element(&test, howMany, 14);
--howMany;
return 0;
}
我得到的输出:
Beginning processing. Array is currently: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Processing done. Array is currently: 0 1 2 3 4 1866386284 6 7 8 9 10 11 12 13 15 16 17 18 19
然后程序在free (*array); 行崩溃。
我希望我的第二行是 0 1 2 3 4 5 6 7 8 9 10 11 12 13 15 16 17 18 19。
我该如何解决我的问题?
【问题讨论】:
-
未定义的行为
-
内容到底是在什么时候出错?这是导致错误的前一行。 BTW:
memmove()的重点是源和目标可以重叠,因为你复制到新内存,你可以使用memcpy()。 -
考虑如果
indexToRemove为零会发生什么。第一个memmove()复制一个数据结构(当它不应该复制时),第二个将sizeOfArray结构复制到包含sizeOfArray-1此类结构的缓冲区/数组中。因此,即使在那种简单的情况下,行为也是未定义的。简而言之:你需要更好地检查你的界限。 -
@Peter 我只是在第一个 memmove() 之前添加了
if(indexToRemove > 0),在第二个之前添加了if(indexToRemove < sizeOfArray - 1),这应该是为了边界吗? -
@Drakalex.:我添加了一个编辑。如果你使用 0 索引应该遵循这些
标签: c arrays pointers struct dynamic-allocation