指针数组*等级[]

时间:2015-12-31 11:48:13

标签: c++ arrays

我可以将两个不同的数组地址插入指针数组,但是当我打印它时,它只给我第一个arrary。而不是他们两个:

 #include <iostream>
using namespace std;

int *readGrades(int *grades[], int size);

#define SIZE 2

void main()
{
    int *grades[SIZE], *length,x;
    length=readGrades(grades, SIZE);

    for (int i = 0; i < SIZE; i++)
    {
        x = *(length+i);
        for (int j = 0; j < x; j++)
            cout << *(grades[i] + j) << endl;
    }
}

int *readGrades(int *grades[], int size)
{
    int num_grades, count[SIZE],j,x;
    for (int i = 0; i < size; i++)
    {
        cout << "How many grades for student " <<i+1<< "?" << endl;
        cin >> num_grades;
        cout << "Insert " << num_grades << " grades\n";

        grades[i] = new int[num_grades];
        for ( j = 0; j < num_grades; j++)
        {
            cin >> *(grades[i] + j);
            x = *(grades[i] + j);
        }
        count[i] = j;
    }
    return count;
}

如何打印两个阵列?

1 个答案:

答案 0 :(得分:3)

您在int*中返回count readGrades,当length被分配count已被销毁时,您有一个悬空指针,导致取消引用时的未定义行为。停止一起使用指针并使用std::vector