Monday, January 16, 2012

C Structure Concepts


1.#include < stdio.h >
struct st
{
    int x;
    struct st next;
};
  
int main()
{
    struct st temp;
    temp.x = 10;
    temp.next = temp;
    printf("%d", temp.next.x);
  
    getchar();
    return 0;
}

Output: Compiler Error
A C structure cannot contain a member of its own type because if this is allowed then it becomes impossible for compiler to know size of such struct. Although a pointer of same type can be a member because pointers of all types are of same size and compiler can calculate size of struct.

Nesting of Structures
struct outer{
int a;
struct inner{
char c;
};
};

It is necessary to assign name of inner structure at the time of declaration other wise we cannot access the member of inner structure. So correct declaration is:
struct outer{
int a;
struct inner{
char c;
}name;
};

Structure & Bit Fields
1.void main()
{
struct employee
{
unsigned id: 8;
unsigned sex:1;
unsigned age:7;
};
struct employee emp1={203,1,23};
clrscr();
printf("%d\t%d\t%d",emp1.id,emp1.sex,emp1.age);
getch();
}
Output: 203 1 23
We can access the data member in same way.
How bit data is stored in the memory:
Minimum size of structure which data member in bit is two byte i.e. 16 bit. This is called word size of microprocessor. Word size depends on microprocessor. Turbo c is based on 8086 microprocessor which word size is two byte.
Bits are filed in from right to left direction 8 bit for id,1 bit for sex and 7 bit for age.

2.void main()
{
struct bitfield
{
unsigned a:5;
unsigned c:5;
unsigned b:6;
}bit;
char *p;
struct bitfield *ptr,bit1={1,3,3};
p=&bit1;
p++;
clrscr();
printf("%d",*p);
getch();
}
Output: 12
Explanation:
Binary value of a=1 is 00001 (in 5 bit)
Binary value of b=3 is 00011 (in 5 bit)
Binary value of c=3 is 000011 (in 6 bit)
In memory it is represented as:
Let address of bit1 is 500 which initialize to char pointer p. Since can is one byte data type so p++ will be 501. *p means content of memory location 501 which is (00001100) and its binary equivalent is 12. Hence output is 12.
 
3.void main()
{
struct bitfield
{
signed int a:3;
unsigned int b:13;
unsigned int c:1;
};
struct bitfield bit1={2,14,1};
clrscr();
printf("%d",sizeof(bit1));
getch();
}
Output: 4
 
4.void main()
{
struct bitfield
{
unsigned a:3;
char b;
unsigned c:5;
int d;
}bit;
clrscr();
printf("%d",sizeof(bit));
getch();
}
Output: 5
Note: (Actual output will 6 due to slack byte ,So Before executing this program first go to option menu then compiler then code generation then select word alignment then press OK)
 
5.void main()
{
struct field
{
int a;
char b;
}bit;
struct field bit1={5,'A'};
char *p=&bit1;
*p=45;
clrscr();
printf("\n%d",bit1.a);
getch();
}
Output: 45 

No comments:

Post a Comment