[英]Struct tm time inside of another struct
作為我作業的一部分,我被要求構建一個命令結構,其中存儲了已執行命令的列表。 提供的說明是:
typedef struct {
char *name;
struct tm time;
int code;
} Command;
Note: struct tm defined in <time.h>
我無法訪問存儲在struct tm time
中的時間值,該時間值存儲在我的Command
結構中。 我的代碼如下:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <time.h>
typedef struct command{
char* name;
struct tm *time;
int code;
} Command;
void add_log(Command command[], int return_code, char name[100]){
time_t current_time;
time(¤t_time);
command[0].code = return_code;
command[0].name = strdup(name);
command[0].time = localtime(¤t_time);
}
int main(){
Command command[10];
add_log(command, 0, "log");
printf("Printing return code\n%d\n", command[0].code);
printf("Printing command name\n%s\n", command[0].name);
char time_log[10];
if (strftime(time_log, 10, "%c", time)){
printf("\nPrinting time log\n");
puts(time_log);
}
else{
printf("FAILED");
}
return 0;
}
我得到的錯誤如下所示:
tester.c: In function ‘main’:
tester.c:37:38: warning: passing argument 4 of ‘strftime’ from incompatible pointer type [-Wincompatible-pointer-types]
37 | if (strftime(time_log, 10, "%c", time)){
| ^~~~
| |
| time_t (*)(time_t *) {aka long int (*)(long int *)}
In file included from tester.c:8:
/usr/include/time.h:90:32: note: expected ‘const struct tm * restrict’ but argument is of type ‘time_t (*)(time_t *)’ {aka ‘long int (*)(long int *)’}
90 | const struct tm *__restrict __tp) __THROW;
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~
Printing return code
0
Printing command name
log
FAILED
我特別關注行note: expected 'const struct tm * restrict' but argument is of type 'time_t (*)(time_t *)' {aka 'long int (*)(long int *)'}
。 如果strftime
的第四個參數在我的情況下是錯誤的,有人能指出正確的參數應該是什么嗎?
問題在這里:
strftime(time_log, 10, "%c", time)
您需要在命令中訪問時間 object 所以您應該這樣做
strftime(time_log, 10, "%c", command->time)
至少這個問題:
OP的代碼command[0].time = localtime(¤t_time);
嘗試
// Pseudo code
struct tm = *struct tm
反而
struct tm * lt = localtime(¤t_time);
if (lt != NULL) {
command[0].time = *lt;
} else {
// Handle conversion error;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.