Here is my code...
#include <stdio.h>
struct one
{
struct two
{
int r;
}*b;
}*a;
void main()
{
//struct two *new = &(*a).b;
//new->r = 10;
//printf("Value: %d", new->r);
a = malloc(sizeof(struct one));
//b = malloc(sizeof(struct two));
(a->b)->r = 10;
printf("Value: %d", (a->b)->r);
return 0;
}
What I am trying here is, defining a structure into a structure. Now both of the objects should be pointers. I want to set the value of r
and then display it.
The only thing I am getting it Segmentation Fault
using gdb
I got following, which seems not helping much..
(gdb) run
Starting program: /home/sujal.p/structtest/main
Program received signal SIGSEGV, Segmentation fault.
0x08048435 in main ()
I want to know how to perform mentioned action and why this thing gets Segmentation fault. I have tried possible ways available on some of the websites including Stackoverflow's some of the questions.
The commented lines are my unsuccessful tried to achieve the goal but failed with the same error.
EDIT After trying below mentioned Techniques..
void main()
{
//struct two *new = &(*a).b;
//new->r = 10;
//printf("Value: %d", new->r);
//a = malloc(sizeof(struct one));
//a my_a = malloc(sizeof*my_a);
//my_a->b = malloc(sizeof *my_a->b);
//my_a->b->r = 10;
//b = malloc(sizeof(struct two));
//(a->b)->r = 10;
//printf("Value: %d", my_a->b->r);
a = (one*)malloc(sizeof(struct one));
a->b = (one::two*)malloc(sizeof(struct one::two));
(a->b)->r = 10;
printf("Value: %d", (a->b)->r);
return 0;
}
I have tried all the mentioned techniques, and they are giving me errors.. The last error I get is as follows..
new.c: In function âmainâ:
new.c:24:7: error: âoneâ undeclared (first use in this function)
new.c:24:7: note: each undeclared identifier is reported only once for each function it appears in
new.c:24:11: error: expected expression before â)â token
new.c:25:13: error: expected â)â before â:â token
new.c:25:20: error: expected â;â before âmallocâ
new.c:28:2: warning: âreturnâ with a value, in function returning void [enabled by default]