0

I'm not positive this is even possible, but I am basically trying to define a struct with an array of the same struct inside of it, like so

struct Node {
    int numMatches = 0;
    Node* leaves[26] = {};
};

Each node would contain a fixed-length array of pointers to other nodes (representing letters). I'm trying to recurse through these nodes, going into the relevant leaf whenever I need. I would initialize a "head" Node* array and bubble down that way. It's seg faulting immediately, and I can see why that might be - it doesn't know how much memory to alloc to an array of such structs. Not quite sure how to solve the problem though.

Pretty simple issue, but I haven't found any C++/C specific threads with this same question.

Thanks!

7
  • 4
    Why not hit compile and see if it works? Commented Nov 2, 2016 at 17:36
  • 2
    of course it does. The array contains pointers to structs, not structs. You have to allocate each one as you want to use it. Commented Nov 2, 2016 at 17:37
  • 1
    Node* leaves[26] = {NULL}; would initialize the array of pointer to NULL. Better than nothing I guess. We would need to see your context code to help you further. Commented Nov 2, 2016 at 17:37
  • 2
    How are you initialize these Node* pointers? Can you provide a minimal reproducible example that reproduces your problem please? Commented Nov 2, 2016 at 17:38
  • @NathanOliver If the code segfaults, they appearantly already compilled the code. Commented Nov 2, 2016 at 17:40

1 Answer 1

1

In your struct you didn't use an array of the same struct, but an array of the pointers to the same struct - and it makes the difference.

Pointers have known length (e. g. 32-bit in 32-bit operating systems) regardless of the object they point to, so your struct simply allocates (probably)

  • 32 bits = 4 bytes for mumMatches
  • 26 * 32 bits = 26 * 4 bytes = 104 bytes for leaves


  • 108 bytes altogether

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.