initial array in size by ref c++

301 views Asked by At

I was asked to create this function:

int * createAndInput(int & size)

The function initializes an array in the size of the value size, gets the values from the user as input, and returns the allocated array and the size by ref.

Here is the code I have so far:

int *creatAndInput(int& size)
{ 
    int arr1[***size***];
    for (int i = 0; i << size; i++)
    {
        cout << "enter index " << (i + 1) << endl;
        cin >> arr1[i]; 
    }
    return (arr1);
}

void main()
{
    cout << "enter size number" << endl;
    int size2 = 10;
    int *size1 = &size2;
    cout << *creatAndInput(size2);
}

image

1

There are 1 answers

0
Andrej Trožić On
#include <iostream>

int* createAndInput(int& size)
{
    int* ptr = new int[size];

    for(int i = 0; i < size; i++){
        std::cout << i+1 << ". element: ";
        std::cin >> ptr[i];
    }

    return ptr;
}

int main(){

    int *ptr, size;

    std::cout << "Size: ";
    std::cin >> size;

    ptr = createAndInput(size);

    for(int i = 0; i < size; i++)
        std::cout << i+1 << ". element: "<< ptr[i] << std::endl;

    delete[] ptr;

    return 0;
}