Gal Chimovich
Gal Chimovich

Reputation: 1

initial array in size by ref c++

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

Upvotes: 0

Views: 405

Answers (1)

Andrej Trožić
Andrej Trožić

Reputation: 21

#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;
}

Upvotes: 0

Related Questions