Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

program crash in accessing struct elements

Tags:

c++

struct

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

like image 816
anonymous38653 Avatar asked Apr 26 '26 15:04

anonymous38653


1 Answers

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.

like image 90
Sam Varshavchik Avatar answered Apr 28 '26 07:04

Sam Varshavchik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!