0

i need to convert time in 12 hr to the 24 hr format.

ive hardcoded the 12 hour time for now to make stuff simpler.

my logic: input sting 07:05:45PM extract last 2 chars. if AM check is first 2 chars are 12.. if yes chance them to 00 else output as it is if PM check if first 2 digits are 12 ..if yes leave as it is if not then add 12 to first 2 digits

 #include<stdio.h> #include<stdlib.h> #include<string.h> char* timeConversion(char* s1) { // input sting 07:05:45PM // extract last 2 chars. // if AM // check is first 2 chars are 12.. if yes chance them to 00 // else output as it is // if PM // check if first 2 digits are 12 ..if yes leave as it is // if not then add 12 to first 2 digits char s[strlen(s1) + 1]; strcpy(s, s1); char suffix[3]; // pm am suffix[0] = s[strlen(s) - 2]; suffix[1] = s[strlen(s) - 1]; suffix[2] = '\0'; char xx[3]; // first 2 nos xx[0] = s[0]; xx[1] = s[1]; xx[2] = '\0'; s[strlen(s1) - 1] = '\0'; s[strlen(s1) - 2] = '\0'; if(strcmp(suffix, "AM") == 0) { if(strcmp(xx, "12") == 0) { s[0] = '0'; s[1] = '0'; strcpy(s1, s); } else { return s1; } } else { if(strcmp(xx, "12") == 0) { strcpy(s, s1); return s1; } else { int n; // 01 - 09 if(xx[0] == '0') { char x = xx[1]; n = x - '0'; // xx = itoa(n); } else { // 10, 11 n = atoi(xx); } n = n + 12; // itoa(n, xx, 10); sprintf(xx, "%d", n); s[0] = xx[0]; s[1] = xx[1]; } } strcpy(s1, s); return s1; } int main() { char *str = "07:05:45PM"; char *str1 = timeConversion(str); printf("%s\n", str1); return 0; } 

Bus error: 10 is what im getting on running the code

3
  • You are not allowed to change s1 inside the function as str points to a string literal which is a constant. You can try: char *str = "07:05:45PM"; ==> char str[] = "07:05:45PM"; but I'm not sure it solves all problems. Commented May 21, 2019 at 8:26
  • "ive hardcoded the 12 hour time for now to make stuff simpler." : Unfortunately that is exactly what has caused your problem! Commented May 21, 2019 at 8:45
  • Since I wrote it before the close, you might as well get the benefit, 12 Hour Time to 24 Hour Time expires: Tue May 28 15:49:54 CDT 2019 Commented May 21, 2019 at 8:50

1 Answer 1

0

The problem is in

 strcpy(s1, s); 

you're essentially trying to write into a pointer to the first element of a string literal. It invokes undefined behaviour.

Check the function call

timeConversion(str); 

where str points to a string literal, and any attempt to modify the contents of a string literal is UB.

What you need to do in timeConversion() function is to:

  • have required amount of memory allocated (call to malloc() is one way)
  • use that to hold the modified output
  • return the pointer to the caller.
  • free the memory once you're done using it.
Sign up to request clarification or add additional context in comments.

Comments