Reputation: 43
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
Reputation: 6606
stem
and temp
are two different variables. :) you are giving memory to temp
and accessing stem
.
Upvotes: 3
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
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
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