简体   繁体   中英

send dynamic array of pointer to function in c++

I trying to send array to function, but my program gets stuck

int main()
{
    int n, i;
    bool random;

    cout << "number of elements in array:"; cin >> n;
    cout << "use random values?"; cin >> random;

    int* arr = new int[n]; //create int array with n size
    init_array(random, n, arr); //fill array using function

    for (i = 0; i <= n; i++) //display array
        cout << " " << arr[i];

    return 0;
}

This function should fill array with random number or input from keyboard

void init_array(bool random, int n, int* arr)
{
    int i;
    if (random)
    {
        srand(time(0)); //initialize random;
        for (i = 0; i < n; i++)
            arr[i] = rand() % 100;
    }
    else
        for (i = 0; i<n; i++)
            cout << "arr[" << i << "]: "; cin >> arr[i];
}

Is there any way send dynamic array to function?

When you do not use brackets after your for-loop, only the first statement is used as a loop:

else
    for (i = 0; i<n; i++)
        cout << "arr[" << i << "]: "; cin >> arr[i];

This loop will attempt to print "arr[#]" n times, and then ask for an input (which will attempt to be placed in the item 1 after the last element in your array (UB).

What you want is this:

else
{
    for (i = 0; i<n; i++)
    {
        cout << "arr[" << i << "]: "; 
        cin >> arr[i];
    }
}

You also have a problem with your output:

for (i = 0; i < n; i++) // <= would attempt to print 1 more item than exists in the array

And just for completeness, most of these issues go away when you use a container that does all of this for you:

int main()
{
    int n = 0;
    bool useRandom = false;
    std::cout << "number of elements in array:"; 
    std::cin >> n;
    std::cout << "use random values?"; 
    std::cin >> useRandom;

    std::vector<int> arr(n);
    init_array(useRandom, arr);

    std::copy(arr.begin(), arr.end(), std::ostream_iterator<int>(std::cout, " "));

    return 0;
}

void init_array(bool useRandom, std::vector<int>& vec)
{
    ::srand(time(0)); //initialize random;
    int n = 0;
    std::transform(vec.begin(), vec.end(), vec.begin(), [&](int i)
    {
        if (useRandom)
        {
            i = rand() % 100;
        }
        else
        {
            std::cout << "arr[" << n++ << "]:  ";
            std::cin >> i;
        }
        return i;
    });
}

Your code is asking for a number at the end because of last cin>>n

fix else part in init_array as:

 else
        for (i = 0; i<n; i++)
            { //Notice braces
             cout << "arr[" << i << "]: ";
             cin >> arr[i];
            }

Also fix:

for (i = 0; i < n; i++) //display array from index 0 to n-1
    cout << " " << arr[i];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM