© 2014 Firstsoft Technologies (P) Limited. login
Hi 'Guest'
Home SiteMap Contact Us Disclaimer
enggedu

C and C++ Interview Questions

6.  How can I access structure fields by name at run time?

Ans:

Build a table of names and offsets, using the offsetof() macro. The offset of field b in struct a is
offsetb = offsetof(struct a, b)

If structp is a pointer to an instance of this structure, and field b is an int (with offset as computed above), b's value can be set indirectly with
*(int *)((char *)structp + offsetb) = value; 

Ex - 1:  What is the output?
main()
{
  struct xx
   {
      int x=3;
      char name[]="hello";
   };
struct xx *s=malloc(sizeof(struct xx));
printf("%d",s->x);
printf("%s",s->name);
}

Ans:
Compiler Error

Explanation:

Initialization should not be done for structure members inside the structure declaration

Ex - 2:  What is the output?
main()
{
struct xx
 {
              int x;
              struct yy
               {
                 char s;
                 struct xx *p;
               };
                         struct yy *q;
            };
            }

Ans:
Compiler Error

Explanation:
in the end of nested structure yy a member have to be declared


SLogix Student Projects
bottom