Hi,

I need to implement a dynamic array of pointers to structures.Here's what I've done

struct node{
        int freq;
        node *lptr;
        node *rptr;
};

class M
{
        private:
        node **A;
        int length;
        public:
        M()
        {
                length=10;
                A=new node*[10];
        }
        M(int a)
        {
                length=a;
                A=new node*[a];
        }

Firstly, am I right?

Now when I use this in a function..

int i;
 for(i=0;i<length;i++)
  A[i]->freq=i;

I get Segmentation Fault.I'm pretty sure im mucking up pointers somewhere.Any help?

Dani AI

Generated

— the segmentation fault happens because the pointers inside your pointer-array never point to valid node objects. is correct in noting there are two distinct allocations: the array that holds pointers, and the actual node instances those pointers must reference.

Two practical fixes:

  • Create an object for each pointer before dereferencing it. If you keep raw pointers, remember to delete every allocated node and the pointer-array itself in your destructor.
  • Prefer modern C++: store nodes by value or use smart pointers in a container so you do not manage raw memory manually. This removes many common bugs (double deletes, leaks, shallow copies).

Example patterns (new content, not shown earlier in the thread):

~M() {
    for (int i = 0; i < length; ++i) {
        delete A[i];
    }
    delete [] A;
}

Or use RAII with the STL:

std::vector<std::unique_ptr<node>> A;
A.reserve(length);
for (int i = 0; i < length; ++i)
    A.emplace_back(std::make_unique<node>());

Final notes and troubleshooting:

  • If you keep raw pointers, initialize all pointer slots to nullptr when allocating the pointer-array so accidental dereferences are easier to spot.
  • Implement or delete copy/assignment (Rule of Three/Five) to avoid shallow-copy bugs.
  • Use tools: run under gdb, Valgrind, or AddressSanitizer to find invalid reads/writes.
  • For std::vector and smart pointers, see cppreference: std::vector and std::unique_ptr.

Recommended Answers

All 3 Replies

>Firstly, am I right?
So far, yes.

>I get Segmentation Fault.
Did you allocate memory to the individual pointer or just the array? There are two steps here, first you allocate memory for the pointers in the dynamic array, then you allocate memory to each pointer to hold a node instance.

ohhh...I did not allocate memory for each pointer to hold a node...so would that be something like...

for(i=0;i<length;i++)
A[i]=new node

???

That's it exactly.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.