I am playing with implementing inheritance in C. I wrote the following two variations of it. Method 1 crashes while running the program, but Method 2 works fine. What am I doing wrong in Method 1?
#include<stdio.h>
#include<stdlib.h>
typedef struct base_class
{
int a;
}Base;
typedef struct derived_class
{
int b;
Base *base_ptr;
}Derived;
int main(void){
Derived *der_ptr;
der_ptr = (Derived *)malloc(sizeof(Derived));
der_ptr->b = 5;
der_ptr->base_ptr->a=10;
printf("%d %d",der_ptr->b,der_ptr->base_ptr->a);
}
#include<stdio.h>
#include<stdlib.h>
typedef struct base_class
{
int a;
}Base;
typedef struct derived_class
{
int b;
Base base_ptr;
}Derived;
int main(void){
Derived *der_ptr;
der_ptr = (Derived *)malloc(sizeof(Derived));
der_ptr->b = 5;
der_ptr->base_ptr.a=10;
printf("%d %d",der_ptr->b,der_ptr->base_ptr.a);
}
Method 1 crashes because of this line of code:
der_ptr->base_ptr->a=10;
Ask yourself: What is the value of der_ptr->base_ptr
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With