指针数组*等级[]

Pointer array *grades[]

本文关键字:等级 数组 指针      更新时间:2023-10-16

我设法将两个不同的数组地址插入指针数组,但当我打印它时,它只给我第一个数组。而不是两者都有:

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

如何打印这两个数组?

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