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?

2
  • Remark: new int(n) doesn't allocate memory for n ints, new int[n] does (even better, scrap int* and use std::vector<int>. Commented Oct 5, 2013 at 8:10
  • 2
    Possible duplicate of How do I declare an array without initializing a constant? Commented Apr 27, 2019 at 19:40

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.