# Functions. Part 2. Functions and arrays. Passing a one-dimensional and multidimensional array to a function. Passing a structure and a class to a function

## Functions. Part 2. Functions and arrays. Passing a one-dimensional and multidimensional array to a function. Passing a structure and a class to a function

This topic is based on the topic: “Functions. Part 1. Function declaration. Actual and formal arguments. Passing arguments to a function by value and by reference. Function prototype“.

##### 1. An example of defining a function that receives an array of integers

To pass an array of numbers to a function, you need to pass a pointer to this array of numbers.

A pointer to an array of numbers is the:

• name of array;
• address of the first element of the array.

Example. Let’s describe the function SumArrayInts(), which receives an array of integers and finds the sum of the items of this array. The function receives 2 parameters:

• array of integers;
• number of items in the array.

Way 1. Passing an array as int A[].

```// A function that counts the sum of elements of an array of integers
//     n - number of array items,
//     A - array of integers
int SumArrayInts(int n, int A[])
{
int i;
int sum = 0; // the sum
for (i=0; i<n; i++)
sum = sum + A[i];
return sum;
}```

Way 2. Passing an array as int *A.

```int SumArrayInts(int n, int *A) // The array is passed as *A
{
int i;
int sum = 0; // the sum
for (i=0; i<n; i++)
sum = sum + A[i];
return sum;
}```

Calling the SumArrayInts() function from another program code.

```// passing an array to a function
int M[5] = { 23, -2, -1, -8, 4 };
int n = 5;
int summa;

summa = SumArrayInts(n, M);     // summa = 16
summa = SumArrayInts(n, &M[0]); // summa = 16```

It should be noted that with this transfer of the array to the function, the items of the array can be changed in the body of the function.

##### 2. Example of passing a character string to a function

A string of characters is an array of elements of type char. Therefore, passing a string of characters to a function as a parameter is exactly the same as in the case of numbers.

A string of characters can be passed to the function in two ways:

• as a char*;
• as a char[].

Example. A function that returns the number of ‘+’ (plus) characters in a string. The end of the string has the character ‘\0’. Therefore, you do not need to pass the length of a string to a function.

Way 1. Definition of the GetNPlus() function. Passing the string as char *.

```// Function that returns the number of '+' characters in a string
int GetNPlus(char *s)
{
char *s2;
int n = 0;
s2 = s;

while (*s2!='\0')
{
if (*s2=='+') n++;
s2++;
}
return n;
}```

The title of the above function could also be defined as follows:

```int GetNPlus(char s[])
{
...
}```

Way 2. Definition of the GetNPlus2() function. Using indexes to access the string characters.

```// Access to symbols of string by index
int GetNPlus2(char *s)
{
int i=0;
int n=0;

while (s[i]!='\0')
{
if (s[i]=='+') n++;
i++;
}

return n;
}```

Calling the GetNPlus2() function from another program code.

```// passing an array to a function
char * str = "+Test + + +++ string .";
int n;
n = GetNPlus2(str); // n = 6```

##### 3. How to pass an array of strings to a function? Example

Example. A function that receives an array of strings and sorts it by the bubble method. The array of strings is passed by the first parameter. The second parameter is the number of rows.

```// Function that receives an array of strings and sorts it by the bubble method
void SortStrings(char * s[], int n)
{
int i, j, k;
char * ts; // additional variable

for (i=0; i<n-1; i++)
for (j=i; j>=0; j--)
{
if (strcmp(s[j],s[j+1])>0)
{
// exchange of pointers
ts = s[j];
s[j] = s[j+1];
s[j+1] = ts;
}
}

// The output is a sorted array of pointers s
return;
}```

The above function uses the strcmp() function. This function compares 2 lines s1 and s2 in lexicographical order:

`n = strcmp(s1, s2);`

and returns value

• >0, if string s1 follows after line s2 in lexicographical order;
• =0, if the strings are equal;
• <0, if the string s1 is before the string s2 in lexicographical order.

Calling a function from another program code:

```// Passing an array of pointers to a function
char * str[] = { "DEF",
"FEC",
"CSE",
"AFE",
"QER" };
int n = 5;
int i;

// function call
SortStrings(str, n);```

##### 4. Example of passing a two-dimensional array as a function parameter

In this example, a function is defined that finds the sum of the elements of a two-dimensional array. The function takes a two-dimensional array of real numbers as a parameter.

```// Function of computing the sum of a two-dimensional array
double Sum2(double A[][3])
{
double s = 0;
int i,j;
for (i=0; i<2; i++)
for (j=0; j<3; j++)
s = s + A[i][j];
return s;
}```

Calling a function from the program code. A two-dimensional array with the name M of size 2×3 is passed to the function.

```// Passing a two-dimensional array as a function parameter
// Two-dimensional array of numbers
double M[][3] = { { 2.78, -3.18, 9.4 },
{ -3.4,   8.8, 0.5 } };
double summa;
summa = Sum2(M);```

##### 5. Example of pass a function of a three-dimensional array of numbers

In this example, the function Sum3() is described, which takes an input parameter as a three-dimensional array of integers. The size of the array is 2×3×4. The function returns the sum of array elements.

```// Passing a three-dimensional array D as a function parameter
// Function calculates the sum of elements of a three-dimensional array
int Sum3(int D[][3][4])
{
int summa = 0; // variable - result
int i, j, k;

// the sum calculation
for (i=0; i<2; i++)
for (j=0; j<3; j++)
for (k=0; k<4; k++)
summa = summa + D[i][j][k];

return summa;
}```

Calling a function from another program code

```// three-dimensional array of numbers
int A[2][3][4];
int i, j, k;
int sum;

// Filling the array A with random values
for (i=0; i<2; i++)
for (j=0; j<3; j++)
for (k=0; k<4; k++)
A[i][j][k] = i+j+k;

// Call a function that calculates the sum of array items
sum = Sum3(A);```

##### 6. How can I pass a structure to a function? Example

As a parameter, the structure can be passed to the function in two ways:

• by the value;
• by the reference (not used in the CLR environment).

For more details on how to pass parameters to a function, see here.

When the structure is passed by value, a copy is made on the stack of all the fields of the structured variable. When the structure is passed to the address, only the address of the structure in memory is passed (a pointer to the structure). This method is more efficient if you need to allocate a lot of memory for the structure fields (the pointer size can be much smaller than the size of the structure variable). A pointer to a structure that is passed to a function can be of two types:

• unmanaged pointer (*);
• managed pointer (^).In this case, the structure should be declared with the keyword ref (see paragraph 7).

Example. Passing of a structural variable (object) by value and by address (the unmanaged pointer * case).

Suppose that outside the class (or in another module) a structure is specified that describes a point on the coordinate plane:

```...

// the structure of type struct MyPoint
struct MyPoint
{
int x;
int y;
};

...```

Let there be given two functions that determine whether the points are equal:

• function Equals(), which as parameters receives 2 structural variables of type MyPoint (passed by value);
• function EqualsP(), which receives 2 pointers to structure variables of type MyPoint (passed by address).
```// A function that determines whether points are equal
// the transfer of structural variables is by value
bool Equals(MyPoint mp1, MyPoint mp2)
{
bool f = false;
if ((mp1.x==mp2.x) && (mp1.y==mp2.y))
f = true;
return f;
}

// function is similar to the Equals function, only
// the transfer of structural variables is realized by the address
bool EqualsP(MyPoint *mp1, MyPoint *mp2)
{
bool f = false;
if ((mp1->x == mp2->x) && (mp1->y = mp2->y))
f = true;
return f;
}```

Then the call to the Equals() and EqualsP() functions can be performed from another program code approximately as follows:

```...

// Structure transfer to a function
MyPoint p1, p2; // structural variables
bool res;

// filling the value of the variable p1
p1.x = 28;
p1.y = -33;

// Filling the value of the variable p2
p2.x = 28;
p2.y = -33;

// transferring a structure to the Equals function by value

res = this->Equals(p1, p2); // res = true
res = Equals(p1, p2);       // res = true - also good

// Passing the address of a structural variable
res = EqualsP(&p1, &p2); // res = true

...```

##### 7. An example of passing a pointer to a reference type structure (ref)

In this example, a transfer to the managed (^) pointer to the structure is demonstrated. The EqualsPRef() function takes two managed (^) pointers to a MyPoint type structure. Function determines the equality of fields of structures to which the pointer points.

MyPoint structure has the following definition:

```ref struct MyPoint
{
int x;
int y;
};```

The definition (implementation) of the EqualsPRef() function:

```// A function that receives two managed pointers (^) at the input
// to structures of reference type.
// Function determines the equality of structures to which the pointers points
bool EqualsPRef(MyPoint ^p1, MyPoint ^p2)
{
bool f = false;
if ((p1->x == p2->x) && (p1->y == p2->y))
f = true;
return f;
}```

Calling the EqualsPRef() function from another program code (for example, the click event handler on the button):

```// if the structure is declared as a reference type
// with the keyword ref
MyPoint mp1; // Managed pointer to the structure
MyPoint mp2;

// memory allocation for structural variables
mp1 = gcnew MyPoint;
mp2 = gcnew MyPoint;

// filling the fields of structure 1
mp1->x = 30;
mp1->y = -30;

// filling the fields of structure 1
mp2->x = 28;
mp2->y = -30;

// the determination of result, a function call
bool res;
res = EqualsPRef(mp1, mp2); // res = false```

##### 8. How to pass a class object as a parameter of a function?

Given a MyPointClass class that describes the coordinates of points on the plane. The class is defined in two modules:

• in the module MyPointClass.h is described the definition of functions and fields of the class;
• in the module MyPointClass.cpp is described the implementation of methods and fields of the class.

The text of the module MyPointClass.h:

```#pragma once

// the class is declared as "managed"
ref class MyPointClass
{
int x;
int y;

public:
MyPointClass(void);
int GetX(void);
int GetY(void);
void SetXY(int nx, int ny);
};```

Текст модуля MyPointClass.cpp:

```#include "StdAfx.h"
#include "MyPointClass.h"

MyPointClass::MyPointClass(void)
{
x = 0;
y = 0;
}

int MyPointClass::GetX(void)
{
return x;
}

int MyPointClass::GetY(void)
{
return y;
}

// set a new value for x and y
void MyPointClass::SetXY(int nx, int ny)
{
x = nx;
y = ny;
}```

Let the EqualsClass() function be described in the main program module (for example, the form class), which compares the fields of the MyPointClass class. The function receives two parameters – managed pointers to the class (^).You can not pass a class as a parameter-value, because the class belongs to a reference type. You need to use managed pointers (^) with the class. More details about managed and unmanaged pointers are described here.

```// Function that takes a pointer to a class as a parameter
// The function compares the fields of class
bool EqualsClass(MyPointClass ^p1, MyPointClass ^p2)
{
int x1, y1, x2, y2;
bool res = false;

x1 = p1->GetX();
y1 = p1->GetY();
x2 = p2->GetX();
y2 = p2->GetY();

if ((x1==x2) && (y1==y2))
res = true;

return res;
}```

Calling the EqualsClass() function from another program code (for example, from the event handler):

```// Passing a class to a function
MyPointClass pc1; // Object, a variable of type class, can not be passed to a function as a parameter
MyPointClass ^pc2 = gcnew MyPointClass(); // A managed pointer to a class can be passed to a function
MyPointClass ^pc3 = gcnew MyPointClass(); // A managed pointer to a class
bool f;

// Setting of values of variables
pc1.SetXY(4, 2);
pc2->SetXY(5, 2);
pc3->SetXY(5, 2);

f = EqualsClass(pc2, pc3); // f = true, it works```

To use class methods, you must first include the MyPointClass.h module:

`#include "MyPointClass.h"`

##### 9. Example of passing a structure to a function by reference (not supported in CLR environment)

The structure can be passed to a function by a reference. Code below declares a structure MyPoint, that passed to EqualsR() function by reference for Win32 type applications. In the CLR environment this way of passing parameters is not supported.

```struct MyPoint
{
int x;
int y;
};

// passing by refernce
bool EqualsR(MyPoint& mp1, MyPoint& mp2)
{
bool res = false;
if ((mp1.x == mp2.x) && (mp1.y == mp2.y))
res = true;
return res;
};```

Use of EqualsR() function in another program code

```bool res;
MyPoint p1, p2;
p1.x = 23; p1.y = 23;
p2.x = 26; p2.y = 23;
res = EqualsR(p1, p2);  // res = false```