I'm busy with an assignment, but I'm not sure how to tackle a problem. As a part of a program I need to write an add function. The goal of the program is to:
Read two integer values n1 and n2 from the command line.
Allocate two integer arrays array1 and array2 of size n1 and n2
inititalize the two arrays with values 0,1....,n1-1 and 0,1....,n2-1
Write an add function with the signature:
void add(... array1, ... n1, ... array2, ... n2, ... array3, ... n3)
The function should provide the following functionality:
- Allocates an interger array array3 of size n3 = max(n1,n2);
- adds the two arrays array1 and array2 element by element into array3;
- adds only the first min(n1,n2) elements and copies the elements from the longer array when the two arrays have different length;
- returns array3 and its length n3 via the fifth and the sixth function argument, respectively. Do not change the signature of the add function.
I'm stuck at the part of the add function. I don't see how array3 must be an input argument, but also needs to be allocated in the function. The same confusion holds for n3.
I got as hint that I need to work with double pointers.
Question: How can I implement the first functionality point of the function, while keeping the function signature the same?
Many thanks in advance :) Nadine
EDIT:
My code so far:
// Include header file for standard input/output stream library
#include <iostream>
// Your implementation of the add functions starts here...
void add(int *array1, int *array2, int **array3){
array1[5] = 20;
}
// The global main function that is the designated start of the program
int main(int argc,char* argv[]){
// Read integer values n1 and n2 from the command line
//int n1;
//int n2;
//n1 = atoi(argv[1]);
//n2 = atoi(argv[2]);
// Allocate and initialize integer arrays array1 and array2
int n1 = 10;
int n2 = 10;
int* array1 = NULL;
array1 = new int[n1];
int* array2 = NULL;
array2 = new int[n2];
for (int x = 0; x<n1; x++)
{
array1[x] = x;
}
for (int y = 0; y<n2; y++)
{
array2[y] = y;
}
int *array3;
// Test your add function
add(array1, array2, &array3);
delete[] array1;
delete[] array2;
delete[] array3;
// Return code 0 to the operating system (= no error)
return 0;
}