Delete an array

Jul 10, 2008 at 6:30am
Hi all, I initialise a structure to store some information on students and I declare an array to store 100 students.

Stdinfo Student[100]

I would like to know if I want to delete a record, how do I do so?

Example

I want to del away the info frm Student[35];
how do I do so?

any help will be much appreciated.
Jul 10, 2008 at 6:33am
You can delete as this:
Student[35] = Student[36];
Student[36] = Student[37];
...............
Student[98] = Student[99];
Jul 10, 2008 at 11:00am
what i mean is iwant the array remain but just the info in the array bein del.
Jul 10, 2008 at 11:30am
...which is exactly what simo110 showed you how to do.

To "remove" an element, you must shift all higher elements down by one, and decrement the variable tracking the number of items in the array.

Hope this helps.
Jul 10, 2008 at 11:31am
That algorithm will fullfill your requirement!
Jul 10, 2008 at 12:49pm
Is there a reason that you cannot use a vector where all this work is already coded for you? Using arrays in C++ is antiquated.
Jul 10, 2008 at 2:02pm
1
2
3
4
5
6
7
8
9
vector< Stdinfo > vs_student;

Stdinfo tmp_info(....);
.........
vs_student.push_back( tmp_info );
.........
vs_student.erase(find(vs_student.begin() + static_cast<vector< Stdinfo >::size_type>(35));
.......


The Student[35] is the position of 36 in the vector or array!

Jul 10, 2008 at 2:10pm
In fact, for dynamic deletion or resizing the pre-sized array/structures etc, data structure would be better idea. That may be a simple linked list, vector, or something like that.
But if your requirement is to have only an array of structures and keep the subscript available but info deleted (ie, reset), then memset() may be helpful to you in that case.

Like, to clear the contents of 36th element (ie, Student[35]), it would look like:

memset(&Student[35], '\0', sizeof(Student));

This would reset the contents in the 36th location of Student structure in memory. Remember, it would be a general reset regardless of the data type stored in it. May not be excellent idea, but it may work for you. Check it out.

And other thing, if the structure object/element has a pointer that has dynamcially allocated memory, then you must deallocate that pointer item first and then reset the memory contents of it. Otherwise, it would be a memory leak (if address is lost then it can not be located/recovered any more).

Good luck :)
Topic archived. No new replies allowed.