I am trying to implement REDEFINES logic used in COBOL in C language.
Below is the COBOL Program:
IDENTIFICATION DIVISION.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 DATE-MMDDYY.
10 DATE-MM PIC 9(02).
10 DATE-DD PIC 9(02).
10 DATE-YY PIC 9(02).
01 SYSTEM-DATE-MMDDYY REDEFINES DATE-MMDDYY PIC X(6).
PROCEDURE DIVISION.
MOVE '011817' TO SYSTEM-DATE-MMDDYY.
DISPLAY 'SYSTEM-DATE-MMDDYY: ' SYSTEM-DATE-MMDDYY.
DISPLAY 'DATE-MM: ' DATE-MM.
DISPLAY 'DATE-DD: ' DATE-DD.
DISPLAY 'DATE-YY: ' DATE-YY.
DISPLAY 'CHANGING DATE-YY = 18'
MOVE '18' TO DATE-YY.
DISPLAY 'New SYSTEM-DATE-MMDDYY: ' SYSTEM-DATE-MMDDYY.
STOP RUN.
And below is the execution of above program:
SYSTEM-DATE-MMDDYY: 011817
DATE-MM: 01
DATE-DD: 18
DATE-YY: 17
CHANGING DATE-YY = 18
New SYSTEM-DATE-MMDDYY: 011818
I understand that UNION in C can be used to achieve similar thing. But it is not working for me.
Below is the C program which I wrote:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
union redef
{
struct date_mmddyy{
char date_mm[2];
char date_dd[2];
char date_yy[2];
}date_mmddyy;
char system_date_mmddyy[6];
};
typedef union redef redef;
int main(){
redef redef;
strcpy(redef.date_mmddyy.date_mm, "01");
strcpy(redef.date_mmddyy.date_dd, "18");
strcpy(redef.date_mmddyy.date_yy, "17");
printf("%s\n",redef.date_mmddyy.date_mm);
printf("%s\n",redef.date_mmddyy.date_dd);
printf("%s\n",redef.date_mmddyy.date_yy);
printf("%s\n",redef.system_date_mmddyy);
strcpy(redef.system_date_mmddyy, "021918");
printf("%s\n",redef.date_mmddyy.date_mm);
printf("%s\n",redef.date_mmddyy.date_dd);
printf("%s\n",redef.date_mmddyy.date_yy);
printf("%s\n",redef.system_date_mmddyy);
return 0;
}
And it runs as below:
011817
1817
17
011817
021918
1918
18
021918
Can you please share some idea?
UPDATE 1:
I have terminated all char array with \0
now. Below is the changed code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
union redef
{
struct date_mmddyy{
char date_mm[3];
char date_dd[3];
char date_yy[3];
}date_mmddyy;
char system_date_mmddyy[7];
};
typedef union redef redef;
int main(){
redef redef;
redef.date_mmddyy.date_mm[2] = '\0';
redef.date_mmddyy.date_dd[2] = '\0';
redef.date_mmddyy.date_yy[2] = '\0';
redef.system_date_mmddyy[6] = '\0';
strcpy(redef.date_mmddyy.date_mm, "01");
strcpy(redef.date_mmddyy.date_dd, "18");
strcpy(redef.date_mmddyy.date_yy, "17");
printf("%s\n",redef.date_mmddyy.date_mm);
printf("%s\n",redef.date_mmddyy.date_dd);
printf("%s\n",redef.date_mmddyy.date_yy);
printf("%s\n",redef.system_date_mmddyy);
strcpy(redef.system_date_mmddyy, "021918");
printf("%s\n",redef.date_mmddyy.date_mm);
printf("%s\n",redef.date_mmddyy.date_dd);
printf("%s\n",redef.date_mmddyy.date_yy);
printf("%s\n",redef.system_date_mmddyy);
return 0;
}
And below is the execution:
01
18
17
01
021918
918
021918
Output goes far away from what it is in COBOL.