I’m supposed to use a function to multiply all elements of an array by 5 and print the numbers after. I don’t understand how to put the array in the function definition.
What i tried:
#include <iostream>
using namespace std;
// TODO - Write your function prototype here
int MultiplyArray(int[], int);
int main()
{
const int SIZE = 10;
int myArray[SIZE] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50};
int multiplyMe = 5;
// TODO - Add your function call here
MultiplyArray(myArray, multiplyMe);
// print the array
for(int i=0; i < SIZE; i++)
{
cout << myArray[i] << " ";
}
cout << endl;
return 0;
}
// TODO - Write your function definition here
int MultiplyArray(int myArray[10], int m) {
for (int i = 0; i <= 10; i++) {
myArray[i] *= m;
}
}
The output:
sh -c make -s
./main
signal: segmentation fault (core dumped)
Expected output:
25 50 75 100 125 150 175 200 225 250
>Solution :
You are very close. Simply remove the 10 from the [] in the function’s parameter type, and use < instead of <= in your function’s loop. Your loop is going out of bounds of the array (look at the loop in main(), it is using < correctly).
int MultiplyArray(int myArray[], int m) {
for (int i = 0; i < 10; ++i) { // <--
myArray[i] *= m;
}
}
That being said, consider passing the array’s size as a parameter, too:
#include <iostream>
using namespace std;
// TODO - Write your function prototype here
int MultiplyArray(int[], int, int);
int main()
{
const int SIZE = 10;
int myArray[SIZE] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50};
int multiplyMe = 5;
// TODO - Add your function call here
MultiplyArray(myArray, SIZE, multiplyMe);
// print the array
for(int i = 0; i < SIZE; ++i)
{
cout << myArray[i] << " ";
}
cout << endl;
return 0;
}
// TODO - Write your function definition here
int MultiplyArray(int myArray[], int size, int m) {
for (int i = 0; i < size; ++i) {
myArray[i] *= m;
}
}