Note that there are some explanatory texts on larger screens.

plurals
  1. POpointers to structs inside union: how to initialize and retrieve struc values
    primarykey
    data
    text
    <p>I have the following simple code. I am trying to understand how I can use structs inside unions and how I can retrieve contents of struct variables in connection with unions.</p> <p>Here is a small sample code I have written. I want to retrieve the "Maker" struct variables from this code. How should I correctly do it? My code here results in segmentation fault.</p> <p><strong>Here is the updated code :</strong> </p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; typedef struct{ char *name; int *wheels; }CarVendor; typedef struct{ char *name; int *wheels; int seats; }BusVendor; typedef union{ CarVendor *carvendor; BusVendor *busvendor; }Maker; typedef struct{ Maker *carType; }Car; typedef struct{ Maker *busType; }Bus; typedef union{ Car *car; Bus *bus; }Vehicle; void fillDetails(Vehicle *vehicle, int type){ if(type == 0){ vehicle-&gt;car-&gt;carType-&gt;carvendor-&gt;name = "car"; int wheel = 4; vehicle-&gt;car-&gt;carType-&gt;carvendor-&gt;wheels = &amp;wheel; } if(type ==1){ vehicle-&gt;bus-&gt;busType-&gt;busvendor-&gt;name = "bus"; int wheel = 6; vehicle-&gt;bus-&gt;busType-&gt;busvendor-&gt;wheels = &amp;wheel; vehicle-&gt;bus-&gt;busType-&gt;busvendor-&gt;seats = 60; } } int main(int argc, char *argv[]) { Vehicle myvehicle; fillDetails(&amp;myvehicle, 0); //get car details filled &amp; retrieve the details as "Maker" struct Maker *maker; maker = (Maker *) malloc(sizeof(Maker)); maker = myvehicle.car-&gt;carType; printf("Name of car =%s", maker-&gt;carvendor-&gt;name); return 0; </code></pre> <p>}</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload