0

Hi this is program I created for making a user defined array.

This is only a small part of my project and I would like to make it into a static function named 'input(n)',where n is the size of the array.

int main() {


    int* a=0;
    int n,x;
    std::cout<<"Enter size ";
    std:: cin>>n;
    std::cout<<"Enter elements ";
    a=new int(n);

    for(int i=0;i<n;i++){
    std::cin>>x;
    a[i]=x;
    }


for(int j=0;j<n;j++ ){std::cout<<a[j];}
getch();         

}

Any hints on how to get it started?

Angersmash
  • 257
  • 3
  • 13
  • Remark: `new int(n)` doesn't allocate memory for n ints, `new int[n]` does (even better, scrap `int*` and use `std::vector`. – Zeta Oct 05 '13 at 08:10
  • 2
    Possible duplicate of [How do I declare an array without initializing a constant?](https://stackoverflow.com/questions/49596685/how-do-i-declare-an-array-without-initializing-a-constant) – Omar Sherif Apr 27 '19 at 19:40

2 Answers2

1
int * input(size_t n)
{
    int *p =new int[n];
    int x;
    for(size_t i=0;i<n;i++)
    {
      std::cin>>x;
      p[i]=x;
    }

    return p;
}

Then,

a=input(n);

Don't forget to free memory.

P0W
  • 46,614
  • 9
  • 72
  • 119
1
#include <iostream>
using namespace std;

static int* getInput(int n){
    int* a=0;
    int x;
    a=new int[n];
    for(int i=0;i<n;i++){
    cin>>x;
    a[i]=x;
    }
    return a;
    }

int main() {
    int *a;
    int n=5;
    a=getInput(n);
    for(int j=0;j<n;j++ )
    {
        cout<<a[j];
    }
    delete[] a;
}

DEMO

Arpit
  • 12,767
  • 3
  • 27
  • 40