Karthik Sivam
Karthik Sivam

Reputation: 43

Error in memory allocation for array of structures

I am working on this code:

struct box
{
    char word[200][200];
    char meaning[200][200];
    int count;
};

struct root {
    box *alphabets[26];
};
root *stem;
box *access;
void init(){
     //cout<<"start";
    for(int i = 0 ; i<= 25; i++){
        struct box *temp =(struct box*)( malloc(sizeof(struct box)*100));
        temp->count = 0;
        cout<<temp->count;
        stem->alphabets[i] = temp;
    }
    //cout<<" initialized";
}

It got compiled without errors, but during its execution it stops at the point where temp is allocated to stem->alphabets[i]. How to fix this?

Upvotes: 2

Views: 218

Answers (4)

Dayal rai
Dayal rai

Reputation: 6606

stem and temp are two different variables. :) you are giving memory to temp and accessing stem.

Upvotes: 3

john
john

Reputation: 88092

You are using pointers without initializing them first. The simple answer is not to use pointers in the first place. I can see no reason for pointers in the code you have posted.

struct box
{
    char word[200][200];
    char meaning[200][200];
    int count;
};

struct root {
    box alphabets[26];
};
root stem;

Much easier.

Upvotes: 0

Erbureth
Erbureth

Reputation: 3423

You need to allocate memory for the stem variable

root * stem = new root();

Don't forget to dealocate:

delete stem;

Better yet, read something about memory allocations in C++

Upvotes: 4

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727137

Make stem a struct, not a pointer:

root stem; // No asterisk

Otherwise, there's no memory allocated to it, so dereferencing it is undefined behavior.

Of course you need to replace stem->alphabets[i] with stem.alphabets[i].

Upvotes: 6

Related Questions