0
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct name
{
   int *a;
   char b[10];
   char c;
};
int main()
{
   struct name *p;
   p = ( struct name * ) malloc ( 3 * sizeof ( struct name ) );
   char *n;
   n = ( char * ) p;

   *n = 275;
   strcpy ( n + ( sizeof ( p->a ) ), "ALL" );
   * ( n + sizeof ( p->a ) + sizeof ( p->b ) ) = 'D';

   * ( n + ( sizeof ( p[0] ) ) ) = 245;
   strcpy ( ( n + sizeof ( p->a ) + sizeof ( p[0] ) ), "IS" );
   * ( n + sizeof ( p[0] ) + sizeof ( p->a ) + sizeof ( p->b ) ) = 'B';

   * ( n + ( sizeof ( p[0] ) + sizeof ( p[0] ) ) ) = 233;
   strcpy ( ( n + ( 2*sizeof ( p[0] ) + sizeof ( p->a ) ) ), "WELL" );
   * ( n + ( 2*sizeof ( p[0] ) + sizeof ( p->a ) + sizeof ( p->b ) ) ) = 'C';

   printf ( "n1 = %d %s %c\n", p[0].a, p[0].b, p[0].c );
   printf ( "n2 = %d %s %c\n", p[1].a, p[1].b, p[1].c );
   printf ( "n3 = %d %s %c\n", p[2].a, p[2].b, p[2].c );
}

This is the program.........u know in line *n =275 will give the output as 19.........here i want to print as 275 what the changes should be done to print 275

Edited by __avd: Added [code] tags.

2
Contributors
1
Reply
3
Views
7 Years
Discussion Span
Last Post by Banfa
0

|That is because *n is a char and 275 is larger than a char. You need to cast to a pointer to int so that you are storing an actual integer.

However I would strongly discourage this whole code structure, directly accessing the byte of members of a structure through a char pointer, in any commercial project.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.