【问题标题】:Accessing Dynamic Arrays Through Pointers通过指针访问动态数组
【发布时间】:2018-03-30 19:15:20
【问题描述】:

对不起,如果这是一个愚蠢的问题,但我是一个学习 C++ 的新手程序员。

我有一个作业,其中为输入 txt 文件提供了 16 行 1-5 位数字,每行最多 5 个数字。我们应该写一个函数 findmax 在 main 中使用,将每行中的最大数字输出到另一个 txt 文件中。

我的代码没有当前的编译错误我只是停留在如何在 main 中实际使用此函数并将其传递到输出文件中。如果这真的很简单,再次抱歉。

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

int *make( int n)
{
#if 0
    int *a = new int[n];
#else
    int a[n];
#endif
    for( int i=0; i < n; ++i) a[i] = i;

    return a;
 }

int findmax(int x1,int x2,int x3,int x4, int x5)
{
    for(int i=0;i<5;i++)
    {
        int n, temp;
        int a[i];
        if(a[i]>temp)
            temp=a[i];
        return temp;
    }

}
int main() 
{
    int n;
    int x1, x2, x3, x4, x5, y1, y2, y3, y4, y5;
    cout << "Enter number of lines n in the input file." << endl;
    cin >> n;
    int *a = make(n);

    for( int i = 0; i < n; ++i) cout << a[i] << " "; cout << endl;

    ifstream infile; infile.open("/home/labs/lab4/lab4_input.txt");
    ofstream outfile; outfile.open("/home/labs/lab4/lab4_output.txt");
    if( !infile.is_open()) cout << "open infile failed\n";

    infile >> x1 >> x2 >> x3 >> x4 >> x5;
    findmax( x1, x2, x3, x4, x5);
    outfile << y1 << " " << y2 << " " << y3 << " " << y4 << " " << y5 << endl;
    infile.close();
    outfile.close();
    return 0;
}

【问题讨论】:

  • 您需要打开您的 C++ 教科书并阅读有关数组的章节。这个网站不能教你这样的基本概念。您的程序完全是偶然编译的(因为您使用了错误的编译标志)。
  • 在您的make 函数中,int a[n]; 创建一个不属于标准 C++ 语言的可变长度数组 (VLA)。在网上搜索“c++ 数组动态内存新”。
  • 使用 std::vector!

标签: c++ arrays pointers dynamic


【解决方案1】:

首先你说你应该读写一个文件,但是当你使用cincout时你实际上是在使用标准输入和输出。您需要研究在 C++ 中读取和写入文件。 其次,在findmax 函数中,您传递了5 个您从未使用过的参数,并声明了一个您从未使用过的变量nmake 函数末尾的循环也没有任何意义。您需要分别读取每一行,将数字存储在一个数组中,然后使用findmax 函数将该数组作为参数传递。然后在输出文件中输出该行的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 2017-11-28
    • 1970-01-01
    相关资源
    最近更新 更多