在C ++中使用for循环打印数组

时间:2018-06-29 16:18:08

标签: c++ arrays class for-loop

我试图照常使用for循环来打印指针数组的值,并且设法打印了存储在一个对象中的值,但是无法打印存储在另一个对象中的值。我的课程是在Predmet.h中定义的:

#include <iostream>
#include <string>

using namespace std;
class Predmet
{
public:
    int numberOfItems;
    string name;

    Predmet();
    ~Predmet();
};

和Plaza.h:

    class Plaza
{
public:
    int length;
    double x;
    double y;

    Plaza();
    ~Plaza();
};

我的main.cpp看起来像这样:

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include "Plaza.h"
#include "Predmet.h"
using namespace std;

int main() {

    int n, m;
    int *numberOfBeaches;
    Plaza *obj1;
    Predmet *obj2;

    cout << "Enter number of beaches (N): ";
    cin >> n;

    obj1 = new Plaza[n];


    for (int i = 0; i < n; i++) {
        cout << "Enter length and coordinates for " << i + 1 << ". beach: " << endl;
        cin >> obj1[i].length;
        cin >> obj1[i].x >> obj1[i].y;
    }
    cout << endl;
    cout << "Enter number of items (M): ";
    cin >> m;

    obj2 = new Predmet[m];


    numberOfBeaches = new int[n];
    for (int i = 0; i < m; i++) {
        cout << "Enter ordinal number of beach for " << i + 1 << ". item: ";
        cin >> numberOfBeaches[i];
        cout << "Enter how much of item you have and name of the item: ";
        cin >> obj2[i].numberOfItems >> obj2[i].name;
    }

    int *p;

    for (int i = 0; i < n; i++) {
        p = find(numberOfBeaches, numberOfBeaches + n, i + 1);
        if (*p == i + 1) {
            for (int j = 0; j < m; j++) {
                cout << i + 1 << ". " << obj1[i].x << " " << obj1[i].y << " D=" << obj1[i].length << " - predmeti: " << obj2[j].numberOfItems << " " << obj2[j].name << endl;
            }
        }

        else {
            cout << i + 1 << ". " << obj1[i].x << " " << obj1[i].y << " D=" << obj1[i].length << " - predmeti: " << endl;
        } 

    }
    delete[] obj1;
    delete[] obj2;
    delete[] numberOfBeaches;
    system("pause");
    return 0;
}

一切工作到现在为止,直到我为obj2 [i] .kolicina和obj2 [i] .opis添加打印,我得到的结果看起来都是奇怪的,并且抛出了此异常,如下所示:

enter image description here

我在做什么错?提前致谢。 编辑:

在评论中提出建议后,我设法修复了代码(上面的更新版本)以正确的方式打印它,只有当我的M> 1(例如M = 2)时,我才能重复打印行吗?我该如何解决?

2 个答案:

答案 0 :(得分:1)

问题出在这一行:

cout << i + 1 << ". " << obj1[i].x << " " << obj1[i].y << " D=" << obj1[i].duljina << " - predmeti: " << obj2[i].kolicina << " " << obj2[i].opis << endl;

obj2被定义为具有m个元素,但是您正在使用i,其值为0 <= i < n。我不知道mn的关系,但这当然是您应该开始的地方。

答案 1 :(得分:1)

obj2包含m个元素:

obj2 = new Predmet[m];

brojPlaze包含n个元素:

brojPlaze = new int[n];

您正在遍历Predmet中的所有obj2

for (int i = 0; i < m; i++) {
    ...
}

在循环中,您访问brojPlaze的元素i

cin >> brojPlaze[i];

但是i0m,并且m可以大于n元素brojPlaze包含的元素。因此,您可能会访问数组外部的元素,这可能会导致很多不良后果……