C Programming - Structures, Unions, Enums - Discussion

Discussion Forum : Structures, Unions, Enums - Point Out Errors (Q.No. 4)
4.
Point out the error in the program?
struct emp
{
    int ecode;
    struct emp e;
};
Error: in structure declaration
Linker Error
No Error
None of above
Answer: Option
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.
Discussion:
9 comments Page 1 of 1.

Gabriele Gualandi said:   1 decade ago
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);

Aakash said:   1 decade ago
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.

Jayu Dhandha said:   1 decade ago
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:   1 decade ago
How it is different from this one and it is valid:

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

Bharath said:   1 decade ago
Inside structure declaration can be done only using the static declaration.

Pinki Diphol said:   1 decade ago
Here compiler can calculate the size 4(2+2), 2 for int and 2 for pointer.

Natasha said:   1 decade ago
Confused can anybody explain properly?

Ruhi Garg said:   1 decade ago
Can anyone show the correct code?

Vish said:   9 years ago
Thank you @Gabriele Gualand.

Post your comments here:

Your comments will be displayed after verification.