Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading