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?
newis not needed in this case. You should allocate it on the stack usingint[] nums[5];instead - it is faster, and doesn't allocate memory on the heap that you need to explicitly delete.*numsis anint. The*is part of the type, not of the variable identifier.int* nums = createArray(). There's no way to know at compile-time from just a pointer to an integer how many integers it points to. And maybe you didn't realize thatsizeofis a compile-time thing, not a run-time thing.