Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove an element from a struct array which has pointers?

This is my structure which has two integer pointers aV and aT.

struct ADJP
{
    int *aV;
    int eV;
    int nV;
    int *aT;
    int nT;
};
ADJP *Umb = NULL;

The allocation process of aV and aT is like this..

    for(int i=0; i<nb; i++)
    {
        Umb[i].aV = new int[N];
        for(int j=0; j<n; j++)
            Umb[i].aV[j] = pIn[i].aV[j];
}

I want to remove one specific element from Umb array. for example I want to remove Umb[5], then how can I remove. I have tried with various mathods but got error due to allocated pointers I think. I have tried with follow method but its not working with this kind of struct array. It is working with struct array having no pointers.

int DeleteStructElement(int Index, ADJP *b, int N, int at)
{
    for(int i=Index; i<N-1; i++)
        memmove(&b[i], &b[i+1], (N-at-1)*sizeof*b);     // moving the terms of array
    N--;                                                // updating new size
    return N;
}

Have any idea how to remove an element from my struct array?

like image 998
maxpayne Avatar asked Jun 09 '26 03:06

maxpayne


1 Answers

You will want to delete the arrays in the deleted element to release their memory:

delete[] b[Index].aV;
delete[] b[Index].aT;

Then, you only have to do a single memmove to remove the element.

memmove(&b[Index], &b[Index+1], (N-Index-1) * sizeof(b[Index])

EDIT: as Mahmoud points out, this doesn't use the at parameter in DeleteStructElement; I'm not sure what you intended that parameter to do.

like image 138
nneonneo Avatar answered Jun 11 '26 16:06

nneonneo