Friday, November 14, 2014

Structure Padding & Dimensional Array Of C Program



Avoid structure padding in C

#include 
#include
#include 
#pragma pack(1)
struct structure1 
{
       int id1;
       int id2;
       char name;
       char c;
       float percentage;
};
struct structure2 
{
       int id1;
       char name;
       int id2;
       char c;
       float percentage;                      
};
int main() 
{
    struct structure1 a;
    struct structure2 b;
    printf("size of structure1 in bytes : %d\n",sizeof(a));
    printf ( "\n   Address of id1        = %u", &a.id1 );
    printf ( "\n   Address of id2        = %u", &a.id2 );
    printf ( "\n   Address of name       = %u", &a.name );
    printf ( "\n   Address of c          = %u", &a.c );
    printf ( "\n   Address of percentage = %u", &a.percentage );
    printf("   \n\nsize of structure2 in bytes : %d\n", sizeof(b));
    printf ( "\n   Address of id1        = %u", &b.id1 );
    printf ( "\n   Address of name       = %u", &b.name );
    printf ( "\n   Address of id2        = %u", &b.id2 );
    printf ( "\n   Address of c          = %u", &b.c );
    printf ( "\n   Address of percentage = %u",&b.percentage ); 
    getchar();
    return 0;
}

Output

size of structure1 in bytes : 14
Address of id1 = 3438103088
Address of id2 = 3438103092
Address of name = 3438103096
Address of c = 3438103097
Address of percentage = 3438103098

size of structure2 in bytes : 14
Address of id1 = 3438103072
Address of name = 3438103076
Address of id2 = 3438103077
Address of c = 3438103081
Address of percentage = 3438103082

Program for one dimensional array in C

#include
#include
int main()
{
int i;
int arr[5] = {10,20,30,40,50};
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50; */
for (i=0;i<5 br="" i=""> {
printf(“value of arr[%d] is %d \n”, i, arr[i]);
   }
}

Output

value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50

Program for two dimensional array in C

#include
#include
int main()
{
int i,j;
int arr[2][2] = {10,20,30,40};
arr[0][0] = 10;
 arr[0][1] = 20;
arr[1][0] = 30;
arr[1][1] = 40;
for (i=0;i<2 br="" i=""> {
for (j=0;j<2 br="" j=""> {
printf(“value of arr[%d] [%d] : %d\n”,i,j,arr[i][j]);
   }
  }
}

Output

value of arr[0] [0] is 10
value of arr[0] [1] is 20
value of arr[1] [0] is 30
value of arr[1] [1] is 40

Program for pointer in C

#include
#include
int main()
{
int *ptr, q;
q = 50;
ptr = &q;
printf(“%d”, *ptr);
return 0;
}                        
Output

50

No comments:

Post a Comment