[英]changing values of struct tm in function
我正在開發一個函數,該函數應提示用戶輸入任意時間和日期。 這些值我想存儲在struct tm中,但是不能正常工作:
struct tm * enter_time_GMT(){
struct tm *TIME;
char input[50];
int check=0, buffer;
printf("date:\n");
do{
printf("day > ");
scanf("%49s",&input[0]);
buffer=atoi(input);
if(buffer>=1 && buffer<=31){
check=1;
/* program crashes here, compiler says TIME uninitialized: */
TIME->tm_mday=buffer;
}
else{
check=0;
printf("wrong input\n");
}
}while(check==0);
/* just a short part of the full function */
return TIME;
}
我正在使用這樣的功能:
int main(){
struct tm *sysTIME; /* why does the compiler want me to use tm* instead of tm? */
char buffer[80];
sysTIME=enter_time_GMT();
strftime(buffer, 80, "%d.%m.%Y %H:%M:%S", sysTIME);
printf("%s\n", buffer);
return 0;
}
令我驚訝的是,我可能會使用類似
TIME->tm_year=12;
在main()中工作,但不在我的函數中工作。 那么,區別在哪里?struct tm和其他結構有什么區別?
當您的編譯器說TIME
未初始化時,這是正確的。 指針TIME
不會指向任何有意義的地方,訪問它可能會導致程序崩潰。
從您的評論中,我看到您還不熟悉指針。 在這種情況下,您可以直接使用struct tm
。 這樣,您就不必擔心內存管理,因為struct
是按值傳遞的。
如果要使用指針,則必須使該指針指向有效內存。 一種獲取方法是使用malloc
或calloc
在堆上分配內存。 然后可以從函數外部訪問該內存,但是當您不再需要它時,應該稍后free
它。
下面的示例程序使用兩種方法: xmas
使用指針,而newyear
使用普通的struct tm
:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
struct tm *xmas(int year)
{
struct tm *t = calloc(1, sizeof(*t)); // must be free'd after use
t->tm_mday = 24;
t->tm_mon = 11;
t->tm_year = year - 1900;
return t; // pointers to memory on the heap can be safely returned
}
struct tm newyear(int year)
{
struct tm t = {0};
t.tm_mday = 1;
t.tm_mon = 0;
t.tm_year = year - 1900;
return t; // structure is returned "by value"
}
int main()
{
struct tm *x = xmas(2014);
struct tm ny = newyear(2015);
char buf[30];
strftime(buf, sizeof(buf), "%D", x);
puts(buf);
strftime(buf, sizeof(buf), "%D", &ny);
puts(buf);
// Free ressources of allocated memory
free(x);
return 0;
}
在您牢牢掌握了指針之前,使用簡單結構可能會更容易(這不僅包括在堆上分配內存)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.