Angersmash
Angersmash

Reputation: 257

A function for user defined array

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?

Upvotes: 0

Views: 115

Answers (2)

Arpit
Arpit

Reputation: 12797

#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

Upvotes: 1

P0W
P0W

Reputation: 47794

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.

Upvotes: 1

Related Questions