anonymous38653
anonymous38653

Reputation: 403

program crash in accessing struct elements

struct a has int b, and pointer to struct as its elements. And program crashes without printing results.

struct a{
    int b{5};
    a* next=new a;
    a(){
        next->b=3;
    }
    
};
int main(){
    a a1;
    cout<<a1.b<<endl;
    cout<<(*(a1.next)).b<<endl;
    return 0;
}

I expected output to be:

5

3

Upvotes: 3

Views: 150

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118435

a* next=new a;

Your a struct has a member called next, which gets default-initialized by new. Every instance of a that your program creates will have a class member called next, which gets initialized by new. That's how classes and default class member initializers work.

This member is, like I said, is another struct a. Which, of course, also has a member called next which will be initialized by new. Just like every instance of struct a, of course.

And the second struct a will also have a next member, like all as do, which will get initialized by new. This third instance of a will have it's own next, which will get initialized by new.

And so on, in perpetuity, until your computer runs out of memory, creating an infinite chain of struct as.

It is not clear what your intent is here, but this answers the question of why your program is crashing.

Upvotes: 2

Related Questions