C Programming - Structures, Unions, Enums - Discussion

4. 

Point out the error in the program?

struct emp
{
    int ecode;
    struct emp e;
};

[A]. Error: in structure declaration
[B]. Linker Error
[C]. No Error
[D]. None of above

Answer: Option A

Explanation:

The structure emp contains a member e of the same type.(i.e) struct emp. At this stage compiler does not know the size of sttructure.

Bharath said: (Sep 4, 2011)  
Inside structure declaration can be done only using the static declaration.

Natasha said: (Aug 14, 2013)  
Confused can anybody explain properly?

Aakash said: (Aug 23, 2013)  
Size of structure can only be known to compiler after the structure has been defined completely struct emp you can now also write.

{
int ecode;
struct emp e;
int a;
};

Which will result into ambiguity while creating object of structure weather to consider int a; as its member or not so cant be declaration of object inside structure.

Ruhi Garg said: (Nov 14, 2013)  
Can anyone show the correct code?

Jayu Dhandha said: (Dec 25, 2013)  
Simple yar.

Here the object of structure is created inside the structure which has no meaning.

Because it is created only in main. So it will create ambiguity so there is an error. :-).

Keshav said: (Jan 7, 2014)  
How it is different from this one and it is valid:

struct test_struct
{
int val;
struct test_struct *next;
};

Pinki Diphol said: (Jul 29, 2014)  
Here compiler can calculate the size 4(2+2), 2 for int and 2 for pointer.

Gabriele Gualandi said: (Apr 2, 2015)  
Consider the three following options (remember to #include<stdlib.h>):

// ALTERNATIVE 1:
// Declare a struct referencing itself with a pointer.

struct myData1{
int data;
struct myData1 *dataPtr;
};

struct myData1 d1;
d1.data = 1;
struct myData1 d2;
d2.data = 8;
d1.dataPtr = &d2;
printf("d1: data: %i, linked data: %i\n",d1.data,(*(d1.dataPtr)).data);

// ALTERNATIVE 2:
// Declare a typedef, that is a struct referencing itself.

typedef struct myData2{
int data;
struct myData2 *dataPtr;
}MYDATA2;
MYDATA2 d21Ptr;
MYDATA2 d22Ptr;
d21Ptr.data = 1;
d22Ptr.data = 8;
d21Ptr.dataPtr = &d22Ptr;
printf("d21: data %i, linked data: %i\n",d21Ptr.data,(*(d21Ptr.dataPtr)).data);

// ALTERNATIVE 3:
// Define a pointer to data-structure, then use it inside it.

typedef struct myData3 * myData3PTR;
struct myData3{
int data;
myData3PTR dataPtr;
};
myData3PTR d31p = malloc(sizeof(struct myData3)); // You are forced to malloc in this case
myData3PTR d32p = malloc(sizeof(struct myData3)); // You are forced to malloc in this case
(*d31p).data = 1;
(*d32p).data = 8;
(*d31p).dataPtr = d32p;
printf("d31: data %i, linked data: %i\n",(*d31p).data,(*((*d31p).dataPtr)).data);

Vish said: (Feb 20, 2017)  
Thank you @Gabriele Gualand.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.