0

Suppose there is pointer to an array of float values: float *source; and we know its size as int sourcesize;

There is an already implemented function which add an element to the souce array from the inputVec:

void addRecord(const float* inputVec, int& sourcesize)
{
   int inputVecSize = sourcesize;
   memmove( (float*)&(source[inputVecSize]), inputVec, sizeof(float));
}

Now, I want to copy 1 element from the mth element of the source array and attach it to the source end. By using the addRecord above, I have implemented a function as below:

// suppose m is smaller than the current sourcesize
void copyRecord(const float* source, int& m)
{
    float* temporary = new float;
    memcpy( temporary, (float*)&(source[m]), sizeof(float));
    addRecord(temporary, sourcesize);
    delete temporary;
}

It seems the memmove call in the addRecord function may share the variable location of temporary. Thus, maybe I should not delete temporary in the end. But I think maybe they do not share the same address, then I should delete temporary in this case.

So, should I delete temporary in the end or not?

Or, is there a better way to copy an element from source array to its end by using function addRecord?

trincot
  • 317,000
  • 35
  • 244
  • 286
lightrek
  • 951
  • 3
  • 14
  • 30
  • 1
    This code has no hope of working if you're copying `m` floats to an arbitrary single float. I'd strongly encourage you to use Standard Library containers like `std::vector` to store this data. – tadman Nov 16 '16 at 22:57
  • 2
    `sizeof(JtFloat32)` and `sizeof(float)` may not be the same - else why have `JtFloat32`? If they differ, `float* temporary = new float; memcpy( temporary, (JtFloat32*)&(source[m]), sizeof(JtFloat32));` is trouble. – chux - Reinstate Monica Nov 16 '16 at 22:58
  • 2
    You need `JtFloat32* temporary = new JtFloat32[m]` at the *absolute least*. You should also change the method signature to `JtFloat32*` to avoid casting. – tadman Nov 16 '16 at 22:58
  • What is `size`, should that be `sourcesize`? – Barmar Nov 16 '16 at 23:00
  • changed my errors – lightrek Nov 16 '16 at 23:01

1 Answers1

1

memmove() copies the contents of the memory that temporary points to. That copy is not dependent on the original temporary, so it's perfectly safe to delete it after calling memmove().

But there's no need for the temporary in the first place, you can copy directly from the original array.

addRecord(&(source[m]), sizeof source[m]);
Barmar
  • 741,623
  • 53
  • 500
  • 612