Updating an array (passed as parameter) inside a C++ function

Advertisements

I have the following declaration and function call:

unsigned int myArray[5] = {0, 0, 0, 0, 0};
ModifyArray(&myArray[0]);

The above code cannot be modified, it is given as is.

I need to write the implementation for ModifyArray to update myArray to contain 1, 2, 3, 4, 5.

I have written it as:

void ModifyArray(unsigned int * out_buffer) 
{
  unsigned int updatedValues[5] = {0, 0, 0, 0, 0};
  updatedValues[0] = 1;
  updatedValues[1] = 2;
  updatedValues[2] = 3;
  updatedValues[3] = 4;
  updatedValues[4] = 5;
  *out_buffer = &updatedValues;
}

This doesn’t really seem to work. I have a feeling that I’m not doing the assignment correctly on the last line of code, however I have tried multiple variations, and it still doesn’t seem to update just element 0 of the array.

What am I doing wrong? Thanks!

P.S.: Please note that the scenario is more complex than presented here. I have simplified for readability purposes, but the code should look very similar to this, just the last assignment should be updated to a correct one if possible.

>Solution :

*out_buffer is an unsigned int.
&updatedValues is an unsigned int(*)[5] – a pointer to an array of five elements – which you can’t assign to an int.

You should not assign any arrays (it’s impossible), you should modify the contents of the given array:

void ModifyArray(unsigned int *out_buffer) 
{
    out_buffer[0] = 1;
    out_buffer[1] = 2;
    out_buffer[2] = 3;
    out_buffer[3] = 4;
    out_buffer[4] = 5;
}

which you can simplify to

void ModifyArray(unsigned int *out_buffer) 
{
    for (int i = 0; i < 5; i++)
    {
        out_buffer[i] = i+1;
    }
}

Leave a ReplyCancel reply