访问结构中数组元素的正确语法?

问题描述 投票:0回答:1

一年级计算机科学学生,第一次在这里发帖。 我有一个结构

struct Student{
    string name;
    int studentID;
    int numTests;
    int *testScores = new int [TESTS]; //Access with <variableName>.*(testScores + 1), <variableName>.*(testScores + 2), etc.
    int avgScore;
};

我在尝试弄清楚如何更改数组中的值时遇到困难。我想我无法弄清楚语法。这就是我正在做的事情,我走在正确的道路上吗?

    cout << "How many tests did this student take: ";
    cin >> numTests;

    //iterate numTests amount of times through dynamic array
    for (int i = 0; i < numTests; ++i)
    {
        cout <<"Enter score #" << i + 1 << ": ";
        cin >> tempScore;
        newStudent.*(testScores + i) = tempScore;
    }
    

如果您能帮助我找出更改数组值的正确方法,我将不胜感激。

我尝试不使用临时值,将其更改为

        cin >> newStudent.*(testScores + i);

连同

        cin >> *newStudent.(testScores + i);

还有其他一些变化,但我似乎无法找到正确的方法。还是新的。

c++ dynamic heap
1个回答
2
投票

首先,“参考数组”是一种令人惊讶的描述方式

testScores
testScores
中的
struct
数据成员具有“指向
int
的指针”类型,并且可能指向您使用
new
表达式分配的数组中的第一个元素。

其次,您可以通过以下方式访问该数组中的元素

newStudent.testScores[i] = tempScore;
// which is equivalent to ...
*(newStudent.testScores + i) = tempScore;

你也可以写

std::cin >> newStudent.testScores[i];

...绕过了对额外局部

tempScore
变量的需要。

进一步说明

© www.soinside.com 2019 - 2024. All rights reserved.