0

I am having a difficult time trying to access *testscores from *stPtr.

#include <iostream>
using namespace std;

struct GradeInfo{
    char name;
    int *testscores;
    double average;
};

int main(int argc, char *argv[]) {
    GradeInfo var;
    *var.testscores = 10;
    cout << *var.testscores;

    GradeInfo *stPtr = &var;

    // This line of code breaks my test program
    cout << stPtr->testscores;

    return 0;
}

I would sincerely appreciate it if you could help me access the pointer to integer variable within the pointer to structure variable I have declared.

underscore_d
  • 6,309
  • 3
  • 38
  • 64
virtual-snake
  • 21
  • 1
  • 4

3 Answers3

1

You should first allocate space for it to store actual data:

*var.testscores = new int[5];

The you can access it:

var.testscores[3] = 100;

Note the -> operator does not dereference the member. You should add an extra asterisk or use brackets:

cout << *stPtr->testscores;
cout << stPtr->testscores[3];

Should be OK by then.

iBug
  • 35,554
  • 7
  • 89
  • 134
  • 2
    And of course, don't forget to `delete[]` that array later. And then realise you should just be using `std::vector` instead. :P – underscore_d Dec 28 '17 at 11:25
0

Your pointer is not initialized. Either initialize it with new or, better, use smart pointers such as unique_ptr which will handle deletion of your data automatically.

Elias Finoli
  • 121
  • 9
0

You this code below. You haven't allocated memory for integer pointer.

Note: Don't forget to release the allocated memory with new.

#include <iostream>

using namespace std;

struct GradeInfo{
    char name;
    int *testscores;
    double average;
};

int main(int argc, char *argv[]) {
    GradeInfo var;
    var.testscores = new int(10);
    cout << *var.testscores << endl;

    GradeInfo *stPtr = &var;

    cout << *(stPtr->testscores) << endl;

    delete(var.testscores);

    return 0;
}
Karthik Kumar
  • 1,375
  • 1
  • 12
  • 29