简体   繁体   English

从C中的动态数组中的特定位置删除元素

[英]Deleting an element from a specific position in a dynamic array in C

I'm having some trouble wrapping my head around pointers and memory management in C.我在用 C 语言处理指针和内存管理时遇到了一些麻烦。

In this particular instance, I'm trying to delete an element from within a dynamically allocated array.在这个特定的例子中,我试图从动态分配的数组中删除一个元素。

Consider the following lines of code:考虑以下代码行:

void deleteElemFromPosition(VectorDinamic *v, unsigned int poz){
int nCap = v->capacity;
Element* nElems = malloc(nCap * sizeof(Element));

int i;
for (i = 0; i < v->lg; i++) {
    if(i!=poz)nElems[i] = v->elems[i];
    else{
            nElems[i]=v->elems[i+1];
            ++i;

    }
}

free(v->elems);
v->elems = nElems;
v->capacity = nCap;
}

This piece creates a copy of the array that I'm trying to copy with one difference.这篇文章创建了一个我试图复制的数组的副本,但有一个区别。 It doesn't store the element at the wanted position, but rather than doing so, it seems to enter an infinite loop, or actually, not infinite but very very big.它没有将元素存储在想要的位置,但不是这样做,它似乎进入了一个无限循环,或者实际上,不是无限而是非常大。 So big that it makes the program crash.大到让程序崩溃。

Any kind of help would be appreciated.任何形式的帮助将不胜感激。

EDIT: Maybe I should have included the definition of the dynamic array from the beginning.编辑:也许我应该从一开始就包含动态数组的定义。 Oh well.那好吧。

VectorDinamic * creazaVectorDinamic() {
VectorDinamic *v = malloc(sizeof(VectorDinamic));
v->elems = malloc(INIT_CAPACITY * sizeof(Element));
v->capacitate = INIT_CAPACITY;
v->lg = 0;
return v;

You have several problems.你有几个问题。 For a start:作为一个开始:

  1. You do not need to malloc() a completely new array then copy things in. Just shuffle down the ones above the element you are deleting using memmove , then realloc to shrink the allocated memory.您不需要malloc()一个全新的数组,然后将内容复制进去。只需使用memmove将要删除的元素上方的元素memmove ,然后realloc以缩小分配的内存。

  2. Your loop increments i twice, once in the for loop, and once in the else clause.您的循环将i增加两次,一次在for循环中,一次在else子句中。

  3. There seems to be some confusion between v->capacity and v->lg . v->capacityv->lg之间似乎有些混淆。 What is the difference between these two?这两者有什么区别?

In general, telling us where and how it crashes would be useful, as would the definition of VectorDinamic (note dynamic is spelt thus).一般来说,告诉我们它在哪里以及如何崩溃会很有用, VectorDinamic的定义也是VectorDinamic (注意dynamic是这样拼写的)。 Try using gdb or similar.尝试使用gdb或类似的。

In this way is very difficult to find the bug.这种方式很难找到bug。 There could be multiple elements that makes your program crash, like the malloc(nCap * sizeof(Element)) that can return null on error, or free(v->elems);可能有多个元素使您的程序崩溃,例如malloc(nCap * sizeof(Element))可以在错误时返回null ,或free(v->elems); if v->elems is statically allocated or if null .如果v->elems是静态分配的,或者如果为null We don't know what is v->lg ... Try to debug with gdb or valgrind .我们不知道什么是v->lg ... 尝试使用gdbvalgrind进行调试。

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

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