Pass array by reference and modify values C++

Rohit

I want to write a function which takes inArray[3] = {1,2,3,4} and an outArray[3], and modifies outArray[3] within the function to now contain values = {3,4,1,2}.

int main{
 int inArray[4] = {1,2,3,4};
 int outArray[4];

 myFunction(&inArray, &outArray);
}

void myFunction(&inArray, &outArray){
  outArray[0] = inArray[2];
  outArray[1] = inArray[3];
  outArray[2] = inArray[0];
  outArray[3] = inArray[1];
}

I'm doing something wrong here, and I don't precisely understand how to pass an array by reference and manipulate the values inside the function.

Vlad from Moscow

The fiunction and its call can look the following way

const size_t N = 4;

void myFunction( int ( &inArray )[N], int ( &outArray )[N] )
{
  outArray[0] = inArray[2];
  outArray[1] = inArray[3];
  outArray[2] = inArray[0];
  outArray[3] = inArray[1];
}

int main()
{
 int inArray[N] = {1,2,3,4};
 int outArray[N];

 myFunction( inArray, outArray );
}

Take into acccount that your definition of an array

int inArray[3] = {1,2,3,4};

contains a typo and will not be compiled. There must be at least like

int inArray[4] = {1,2,3,4};

or

int inArray[] = {1,2,3,4};

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Pass Array by Reference in C

From Dev

VBA Pass Array By Reference and Modify Contents

From Dev

Pass array by reference in C++

From Dev

pass and modify char array[][] in function C

From Dev

Modify array of hashes by reference

From Dev

C++ - Pass by Reference, Weird Thing for Array

From Dev

C++ pass an array of bitfields by reference

From Dev

How to pass array element by reference in c++?

From Dev

C++ How to pass array by reference to function

From Dev

How to pass Dynamic Array by reference C++

From Dev

Pass value by reference to a thread and modify

From Java

Swift: Pass array by reference?

From Dev

pass array by reference in golang

From Dev

PowerShell pass array as a reference

From Dev

Modify values of array / multidimensional array

From Dev

Modify values of array / multidimensional array

From Dev

C# pass element of value type array by reference

From Dev

C++ Pass by reference a single element array - It's factible?

From Dev

Passing and changing an array, with pass by reference, using pointers in C

From Dev

Pass double array by reference from C to Delphi DLL

From Dev

How to pass a dynamic array out of function by reference c++

From Dev

If we pass an array to a function in C, is it always passed by reference?

From Dev

Pass by pointer/pass by reference in C

From Dev

Pass by const reference in C

From Dev

Pass char[] as reference in c

From Dev

C pass char as reference

From Dev

C pass reference to parameter

From Dev

Pass by reference in C++?

From Dev

Values of Array are changed even though not passed a reference C#