动态分配的数组

问题描述 投票:0回答:2

我正在学习指针,但是我坚持动态分配数组。

下面的代码提供了一个功能,可找到具有最低值的元素。动态分配的数组作为参数传递给它。

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

但它返回此错误:

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

如何将该数组传递给函数?

只是出于好奇:如果我的数组由5个元素组成,为什么for循环允许我输入4个值?

c++ arrays function parameters heap-memory
2个回答
4
投票

如何将该数组传递给函数?

[nums已经是类型int*,您无需取消引用它:

findMin(nums, nums_size);

如果我的数组由5个元素组成,为什么for循环允许我输入4个值?

int nums_size = sizeof(*nums);不执行您认为的操作。它等效于sizeof(nums[0]),等效于sizeof(int),在您的计算机上恰好等于4。无法提取在堆上分配的数组大小,您需要自己保存大小:

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

-1
投票
#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 = 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;
}

上面的代码工作正常。您的错误是将数组传递给函数。

也要添加-

您的代码仅进行了4次迭代,因为coz sizeof(*nums)返回了可以存储在* nums数组中的元素数,即4,4。因此,我对循环中断条件进行了较小的更改,现在它可以正常工作。

© www.soinside.com 2019 - 2024. All rights reserved.