0

Here's my simplified program:

#include <iostream>
using namespace std;

int main () {

    struct A {
        int num;
    };
    struct B {
        A * a;
    };
    struct C {
        int number_of_entries;
        struct B **entry_hash;
    };

    C *c;
    int size = 5;

    cout << "Entering data\n";
    for (int i = 0; i < size; i++){
        cout << "loop num: " << i << "\n";
        c->entry_hash[i]->a->num = i*i;
        c->number_of_entries++;
    }
    cout << "Finished entering data\n";

    cout << "Getting data\n";
    for (int i = 0; i < c->number_of_entries; i++){
        cout << "loop num: " << i << "\n";
        cout << "num: " << c->entry_hash[i]->a->num << "\n";
    }
    cout << "Finished getting data\n";

    return 0;
}

Program output:

Entering data
loop num: 0
Segmentation fault

I'm trying to write information, then retrieve it through these data structures, but I'm clearly doing it wrong and I don't understand why.

The actual program I'm working with is more complicated (though similar core structure), and the data is already loaded for me, I'm just trying to retrieve it.

Otherness
  • 385
  • 2
  • 16
  • 2
    Ask yourself: In `C *c;` what `C` object does `c` point to? – NathanOliver Apr 28 '20 at 20:18
  • `c` is a pointer, but it doesn't point to anything. You haven't allocated memory for it, and even if you had it would require additional work to set up `entry_hash`. In this example, why use a pointer and not just `C c;`? – jtbandes Apr 28 '20 at 20:19
  • Right, so I'm not sure how to do that, but in my actual case the data has already been sent into c, and I'm just trying to access it. Is my "Getting data" loop also incorrect had the data been loaded in correctly? – Otherness Apr 28 '20 at 20:22
  • @NathanOliver it's pointing to the beginning of an array of struct C objects, right? – Otherness Apr 28 '20 at 20:24
  • @Otherness Not in the code you've posted. Maybe in your real code, who knows. – john Apr 28 '20 at 20:27
  • @Otherness No, it points to garbage. Unless you tell it to point to an array, then it basically points to nothing. – NathanOliver Apr 28 '20 at 20:28

0 Answers0