gpt4 book ai didi

c++ - 将空数组传递给函数、在该函数中输入值并返回值的示例

转载 作者:行者123 更新时间:2023-11-30 03:28:11 28 4
gpt4 key购买 nike

我应该在主函数中创建一个空数组,然后使用两个单独的函数来 1. 接受输入到数组中,然后 2. 显示数组的值。

这是我想出的,我遇到了从“int”到“int*”的无效转换 [-fpermissive] 的转换错误。但是,我们的类(class)要到两周后才能接触到指针,而这将在下周到期,所以我假设我们还没有开始使用指针。

#include <iostream>
#include <iomanip>
using namespace std;

int inputFoodAmounts(int[]);
int foodFunction(int[]);


int main()
{

int num[7];

cout << "Enter pounds of food";
inputFoodAmounts(num[7]);
foodFunction(num[7]);

return 0;

}

int inputFoodAmounts(int num[])
{
for (int i = 1; i < 7; i++)
{
cout << "Enter pounds of food";
cin >> num[i];
}
}

int foodFunction(int num[])
{
for (int j = 1; j < 7; j++)
{

cout << num[j];
}
return 0;
}

最佳答案

你应该通过 num功能; num[7]表示数组的第 8 个元素(并且它超出了数组的范围)但不是数组本身。改成

inputFoodAmounts(num);
foodFunction(num);

顺便说一句:for (int i = 1; i < 7; i++)看起来很奇怪,因为它只将数组从第 2 个元素迭代到第 7 个元素。

关于c++ - 将空数组传递给函数、在该函数中输入值并返回值的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46801712/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com