UnoaCaso
UnoaCaso

Reputation: 47

Dynamically allocated array

I'm learning pointers in but I'm stuck on dynamic allocation of arrays.

The code below provides a function to find the element with the lowest value. A dynamically allocated array is passed as a parameter to it.

#include <cstdlib>
#include <iostream>

using namespace std;

int findMin(int *arr, int n);

int main()
{
    int *nums = new int[5];
    int nums_size = sizeof(*nums);

    cout << "Enter 5 numbers to find the minor:" << endl;
    for(int i = 0; i < nums_size; i++)
        cin >> nums[i];

    cout << "The minor number is " << findMin(*nums, nums_size);

    delete [] nums; 

    return 0;
}

But it return this error:

error: invalid conversion from ‘int’ to ‘int*’ [-fpermissive]

How can I pass that array to the function?

Just for curiosity: why the for loop allows me to enter 4 value if my array is made up of 5 elements?

Upvotes: 0

Views: 493

Answers (2)

Abhishek Bhagate
Abhishek Bhagate

Reputation: 5766

#include <cstdlib>
#include <iostream>

using namespace std;

int findMin(int *arr, int n){
    int mn=INT_MAX;
    for(int i=0;i<n;i++){
        if(arr[i]<mn){
            mn=arr[i];
        }
    }
    return mn;
};

int main()
{
    int nums_size = 5; 
    int *nums = new int[nums_size];

    cout << "Enter 5 numbers to find the minor:" << endl;
    for(int i = 0; i < nums_size; i++)
        cin >> nums[i];

    cout << "The minor number is " << findMin(nums, nums_size);

    delete [] nums; 

    return 0;
}

The above code works fine. Your error was in passing the array to the function.

Also to add -

Your code made only 4 iterations coz sizeof(*nums) returned the size of base index element pointed by pointer, i.e ,sizeof(num[0]). So I made a minor change and now it works fine.

Upvotes: 0

Yksisarvinen
Yksisarvinen

Reputation: 22221

How can I pass that array to the function?

nums is already a type int*, you don't need to dereference it:

findMin(nums, nums_size);

why the for loop allows me to enter 4 value if my array is made up of 5 elements?

int nums_size = sizeof(*nums); does not do what you think it does. It's equivalent to sizeof(nums[0]), which is equivalent to sizeof(int), which happens to be equal to 4 at your machine.
There is no way to extract size of array allocated on the heap, you need to save the size on your own:

int nums_size = 5;
int* nums = new int[nums_size];

Upvotes: 9

Related Questions