adplus-dvertising

the programme doesn't want to accept the array with a variable lenth in the function in c++

Asked 2 months ago
Viewed 25 times
c++

#include <iostream>

using namespace std;
int read ()
{ 
    int num;
    cout << "enter a number \n";
    cin >> num;
    return num;
}
int arrayNum (int num)
{ 
    int array[num];
    for (int i = 0 ; i <= num - 1 ; i++)
    {
        cout <<"enter number "<< i+1 <<endl;
        cin>> array[i];
    }
    return array[num];
}
void SumArray (int array[])
{  int num;
  
   int sum = 0;
   for (int i = 0 ; i <= num - 1 ; i++)
   {
      sum = sum + array[i];
   }
   cout << sum <<endl;
}
int main ()
{
SumArray (arrayNum (read()));
}

i have a problem with the array variable paramater in function SumArray , also it give me this massege :"initializing argument 1 of 'void SumArray(int*)'void SumArray (int array[])". and this : " invalid conversion from 'int' to 'int*' [-fpermissive] SumArray (arrayNum (read()));"

asked 2 months ago

Correct Answer

In c++, a static array cannot be of variable size because the compiler creates the array at compile time. In order to have an array of variable size, you must use a pointer and create a dynamic array using the new keyword.

For example:

int * CreateAndFillArray(int size)
{
   int * ptr = new int[size]
   for (int i = 0 ; i < size ; i++)
   {
      cout << "Enter Number " << i << ":";
      cin >> ptr[i];
   }

   return ptr;
}

int main()
{
  int size = 0;
  cout << "Enter array size: ";
  cin >> size;
  int * ptr = CreateAndFillArray(size);


  // Do what you want with array


  // Must delete once complete
  delete ptr[size];
}

The error Initializing argument 1 of 'void SumArray(int*)'void SumArray (int array[])". and this : " invalid conversion from 'int' to 'int*' [-fpermissive] SumArray (arrayNum (read())); means that you cannot convert an int to an int pointer. arrayNum is returning an int, not an int[] or an int array.

answered 2 months ago