zorro47
zorro47

Reputation: 221

How to delete the last element from array with pointers in C++?

I try to build a function which deletes the last element of an array. So I need an input array and its dimension, then delete the last term and obtain a new output array. I don't want that. My goal is to somehow make the output array the new input array. In other words, I want to overwrite the input array with the output array.

So if dimension is 4, I don't want to have a 4-dim array in the memory but only 3-dim table after the deletion.

void del (int* ptr_array, int dim) {
 int* temp = ptr_array; //Hold the very first address of the input array.
 ptr_array = new int[dim - 1]; // Let the address of the input array be 
                               // the address of new output array. Overwritting.

 for (int i = 0; i < dim - 1; i++) {
     ptr_array = (temp+i); // Will it remember what is temp+1 if I have 
                           // already overwritten the arrays?
     ptr_array++;
 }
 //delete[] ptr_array; - this one is out of the questions - deletes now the input table.
}

Can you tell me what is wrong with this code? - in fact it doesn't change anything

Upvotes: 0

Views: 2101

Answers (1)

bruno
bruno

Reputation: 32586

in you function

 for (int i = 0; i < dim - 1; i++) {
     ptr_array = (temp+i); // Will it remember what is temp+1 if I have 
                           // already overwritten the arrays?
     ptr_array++;
 }

does nothing, you wanted

 for (int i = 0; i < dim - 1; i++) {
   ptr_array[i] = temp[i];
 }

Note the delete in your comment is invalid because you do not delete the result of a new[] but a pointer inside the allocated array

If the call is like

int * v = ...;

del(v);

// here v is unchanged

probably you wanted to modify v, in that case you can return the new array or to use an input-output variable using a reference

First possibility :

int* del (int* ptr_array, int dim) {
  int* new_array = new int[dim - 1]; 

  for (int i = 0; i < dim - 1; i++) {
     new_array[i] = ptr_array[i];
  }
  delete[] ptr_array;
  return new_array;
}

with

int * v = ...;

v = del(v);

Second possibility

void del (int*& ptr_array, int dim) {
  int* new_array = new int[dim - 1]; 

  for (int i = 0; i < dim - 1; i++) {
     new_array[i] = ptr_array[i];
  }
  delete[] ptr_array;
  ptr_array = new_array;
}

with

int * v = ...;

del(v);
// here v is the new array

Warning these codes suppose the input array has at least one element


However the use of an std::vector<int> does all of that for you and is more practical to use

std::vector<int> v;
...
v.resize(v.size() - 1);

or

std::vector<int> v;
...
v.pop_back();

Upvotes: 3

Related Questions