-1

When inputting a array in c++ the element in 0th position will become the length of the array. have two functions to input and print the array when print function calls the output array has always the array length in 0th position.

#include<iostream>
using namespace std;
int getArray(int array[])
{
  int len;
  cout << "Enter the length of the array" << endl;
  cin >> len;
  cout << "Enter the elements in the array" << endl;
  for (int i = 0; i < len; ++i)
  {
    cin >> array[i];
  }
  return len;
}
void printArray(int array[], int len)
{
  for (int i = 0; i < len; i++)
  {
    cout << array[i];
  }
}
int main(int argc, char const *argv[])
{

  int array[] = {};
  int len = getArray(array);
  printArray(array, len);
  return 0;
}
Anand S
  • 15
  • 2
  • Welcome to Stack Overflow. Please read [the help pages](http://stackoverflow.com/help), take the SO [tour], read [ask], as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Lastly, what is your question? What is the problem with the code you show? Please [edit] your question to improve it. – Some programmer dude Oct 16 '21 at 09:38
  • 1
    You're not asking a question actually, but I believe you want to learn how to deal with dynamically allocated arrays in c++. Best advice I can give about this is: Ditch c-style arrays completely in favor of `std::vector` for dynamic, and `std::array` for fixed size arrays. – πάντα ῥεῖ Oct 16 '21 at 09:49

1 Answers1

0

In C++, the size of an array must be a compile time constant. So you cannot write code like:

int n = 10;
int arr[n];    //incorrect

Correct way to write this would be:

const int n = 10;
int arr[n];    //correct

For the same reason the following code (last statement) is incorrect :

int k;
cin >> k;
int arr[k]; //incorrect because k must be a compile time constant

You can see that this results in a problem here.

You should use std::vector for this purpose.

Using std::vector, your implementation would look like:

#include<iostream>
#include <vector>
using namespace std;
//passing vec by reference
int getArray(std::vector<int> &vec)
{
  int len;
  cout << "Enter the length of the vector" << endl;
  cin >> len;
  cout << "Enter the elements in the vector" << endl;
  int element;
  for (int i = 0; i < len; ++i)
  {
      cin >> element;
    vec.push_back(element);//use push_back to add element to vector
  }
  return len;
}
//passing vec by reference
void printArray(std::vector<int> &vec, int len)
{
  for (int i = 0; i < len; i++)
  {
    cout << vec[i]<<std::endl;//use vec[i] to access ith element
  }
}
int main()
{

  std::vector<int> vec;
  int len = getArray(vec);
  printArray(vec, len);
  return 0;
}

You can see the output here.

Note

You can simply take the input in the main() itself instead of calling another functions. Similarly for printing the vector. But i have given the code according to your implementation.
Jason
  • 36,170
  • 5
  • 26
  • 60