Учитывая, что время в -часовом формате AM / PM, преобразовать его в военное (24-часовое) время. - PullRequest
0 голосов
/ 02 августа 2020

Я пытаюсь решить эту задачу на хакерранке, но при отправке решения возникают проблемы. Вот мое решение и полученная ошибка, я хотел бы, чтобы кто-то указал на мои ошибки и, если возможно, дал лучшее решение этого вопроса. (TimeConversion () - единственный код, который пользователь должен выполнить, все остальные функции встроены)

    #include <assert.h>
    #include <limits.h>
    #include <math.h>
    #include <stdbool.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    char* readline();
    
    char* timeConversion(char* s) 
    {
        int hr;
        char h[2],mr, hrs[2],m[6];
        mr=s[8];
        for(int i=0; i<2; i++)
            {h[i]=s[i];}
        for(int i=0; i<5; i++)
            {m[i]=s[i+3];}
    
        hr= atoi(h);
    
        if((mr=="A")&&(hr==12))
            {strcpy(hrs, "00");}
        
        if((mr=='P')&&(hr!=12))
            {
                hr=hr+12;
                itoa(hr,hrs,10);  
            
            }
        return strcat(hrs,m);
    
    
    
    }
    
    int main()
    {
        FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");
    
        char* s = readline();
    
        char* result =  timeConversion(s);
    
        fprintf(fptr, "%s\n", result);
    
        fclose(fptr);
    
        return 0;
    }
    
    char* readline() {
        size_t alloc_length = 1024;
        size_t data_length = 0;
        char* data = malloc(alloc_length);
    
        while (true) {
            char* cursor = data + data_length;
            char* line = fgets(cursor, alloc_length - data_length, stdin);
    
            if (!line) { break; }
    
            data_length += strlen(cursor);
    
            if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; }
    
            size_t new_length = alloc_length << 1;
            data = realloc(data, new_length);
    
            if (!data) { break; }
    
            alloc_length = new_length;
        }
    
        if (data[data_length - 1] == '\n') {
            data[data_length - 1] = '\0';
        }
    
        data = realloc(data, data_length);
    
        return data;
    }

Это ошибка, которую я получил

Solution.c: In function ‘timeConversion’:
Solution.c:38:11: warning: comparison between pointer and integer
     if((mr=="A")&&(hr==12))
           ^~
Solution.c:38:11: warning: comparison with string literal results in unspecified behavior [-Waddress]
Solution.c:44:13: warning: implicit declaration of function ‘itoa’; did you mean ‘atol’? [-Wimplicit-function-declaration]
             itoa(hr,hrs,10);
             ^~~~
             atol
In file included from /usr/include/string.h:494,
                 from Solution.c:7:
In function ‘strcpy’,
    inlined from ‘timeConversion’ at Solution.c:39:10:
/usr/include/x86_64-linux-gnu/bits/string_fortified.h:90:10: warning: ‘__builtin___memcpy_chk’ forming offset 3 is out of the bounds [0, 2] of object ‘hrs’ with type ‘char[2]’ [-Warray-bounds]
   return __builtin___strcpy_chk (__dest, __src, __bos (__dest));
          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Solution.c: In function ‘timeConversion’:
Solution.c:29:19: note: ‘hrs’ declared here
     char h[2],mr, hrs[2],m[6];
                   ^~~
/usr/bin/ld: ./cct5tsGb.o: in function `timeConversion':
/tmp/submission/20200802/11/40/hackerrank-a082dac4956371ebbffb5bdc5098ce57/code/Solution.c:44: undefined reference to `itoa'
collect2: error: ld returned 1 exit status

1 Ответ

0 голосов
/ 02 августа 2020

Не смотря на то, что делает код, я могу указать:

Solution.c:38:11: warning: comparison between pointer and integer
     if((mr=="A")&&(hr==12))
           ^~

Вы сравниваете char с char *. Вы должны сравнить, как показано ниже.

 if((mr=='A')&&(hr==12))

Другая проблема здесь:

{strcpy(hrs, "00");}

Переменная hrs имеет размер всего 2 байта, но вы пытаетесь записать 3 байта: 0, 0 и нулевой терминатор. Вам необходимо изменить размер переменной на 3.

Что касается предупреждения «itoa », см. Следующее: Где функция itoa в Linux?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...