Home > Enterprise >  C program: memcpy is copying weird data
C program: memcpy is copying weird data

Time:11-13

C program: The memcpy function seems to be copying the wrong data. The purpose is to take a date parameter of character data (EX: "2019-01-06-20.03.29.004217") and convert it to YYYYMMDD format as an integer. My goal is to read only the numbers for year, month, and day when storing them as a string. Then, concatenate all into a single string. Finally, I want to convert the YYYYMMDD string to an integer and return it.

When executed, I only see the year being returned. Is it something that C isn't recognizing? I'm lost as to why this is happening. Please assist.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int getNumDate2 (char *dte);
    

int main()
{
    char prodDate[26   1];
    strcpy(prodDate,"2019-01-06-20.03.29.004217");// original date of character data

       printf("%d", getNumDate2(prodDate));

    return 0;
}

int getNumDate2(char *dte)
{
  static char orig_date[26   1];
  static char new_date[8   1];
  static char year[4   1];
  static char mth[2   1];
  static char day[2   1];
  int new_date_num;

  
  strcpy(orig_date, dte);//store original characters from date
  memcpy(year, orig_date, sizeof(year));//copy year
  memcpy(mth, orig_date 5, sizeof(mth));//copy month  
  memcpy(day, orig_date 8, sizeof(day));//copy year
  
  strcat(new_date, year);//concat date
  strcat(new_date, mth);
  strcat(new_date, day);
  sscanf(new_date,"%d", &new_date_num);//convert string YYYYMMDD to integer YYYYMMDD
  
  return new_date_num;  
}

CodePudding user response:

Why not use some of what scanf can do:

int getNumDate2(char *dte) {
    int year, month, day;
    sscanf(dte, "%d-%d-%d", &year, &month, &day);
    return (year*100 month)*100 day;
}
  •  Tags:  
  • c
  • Related