Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Getting values from the Structure

Status
Not open for further replies.

sajiv77

Programmer
Jan 2, 2002
14
IN
See the program below and see the output.

#include <stdio.h>
#include <string.h>
#define SIZENUMBER 15

typedef unsigned char byte;

typedef struct
{
byte trans_no[SIZENUMBER];
byte s_no[2];
byte abc;
}XYZ;

main()
{
XYZ xy;
FILE *fp,*fp1;

memcpy(xy.trans_no,&quot;M02031315A0008&quot;,15);
xy.s_no[2] = 12;
xy.abc = 11;


printf(&quot;Number is %s \n&quot;,xy.trans_no);
printf(&quot;Number 2 is %d \n&quot;,xy.s_no[2]);
printf(&quot;Number 3 is %u \n&quot;,xy.abc);

fp = fopen(&quot;testfile&quot;,&quot;w&quot;);
fwrite(&xy,sizeof(XYZ),1,fp);
fclose(fp);
fp1 = fopen(&quot;testfile&quot;,&quot;r&quot;);
fread(&xy,sizeof(XYZ),1,fp1);
printf(&quot;Number from XYZ is %s \n&quot;,xy.trans_no);
printf(&quot;Number 2 XYZ is %d\n&quot;,xy.s_no[2]);
printf(&quot;Number 3 XYZ is %d\n&quot;,xy.abc);

fclose(fp1);
}


I am getting the output as
Number is M02031315A0008
Number 2 is 1
Number 3 is 1
Number from XYZ is M02031315A0008
Number 2 XYZ is 1
Number 3 XYZ is 1
though i should get the values of s_no as
12.
Is there anything wrong in the way i am filling these structures.I need to have all these varieties of elements in my program.

Thanks
 
You defined s_no as a two-byte char array. that is , s_no[0] and s_no[1]. s_no[2] is out of the index range and has exactly the same address as that of abc. That you set a value to abc, also means you set a value to s_no[2].
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top