time_t 和 char* 变量意外被覆盖

time_t and char* variable is unexpectedly getting overwritten

以下代码

{
    time_t t;
    t = time(NULL);
    char *A;
    A = ctime(&t);
    printf("%s -\n", A);
    sleep(2);
    time_t t1;
    t1 = time(NULL);
    printf("%s HERE A =\n", A);
    char *B = ctime(&t1);
    printf("%s HERE B =\n", B);
    printf("%s\n", B);
}

有输出

Sat Mar 30 19:10:33 2019
 -
Sat Mar 30 19:10:33 2019
 HERE A =
Sat Mar 30 19:10:35 2019
 HERE B =
Sat Mar 30 19:10:35 2019

那么变量 A 是如何改变的?我应该怎么做才能使 A 保持固定值

char *A; 更改为 const char *A; 没有帮助

预计

Sat Mar 30 19:10:33 2019
 -
Sat Mar 30 19:10:33 2019
 HERE A =
Sat Mar 30 19:10:33 2019
 HERE B =
Sat Mar 30 19:10:35 2019

所以,ctime returns 一个指向字符串的指针。您将该指针分配给 A 和 B。在这种情况下,它返回相同的指针,这意味着 A 和 B 指向内存中的相同地址。如果你添加代码来打印地址,你可以看到这个:

printf("A=0x%x, B=0x%x", A, B);

time 的手册页解释说这是需要注意的行为:

The return value points to a statically allocated string which might be overwritten by subsequent calls to any of the date and time functions. The function also sets the external variables tzname, timezone, and daylight (see tzset(3)) with information about the current timezone. The reentrant version ctime_r() does the same, but stores the string in a user-supplied buffer which should have room for at least 26 bytes. It need not set tzname, timezone, and daylight.

因此,要解决此问题,您可以使用 ctime 的可重入版本,ctime_r:

char C[27];
ctime_r(&t1, &C);

您也可以使用 strcpystrdup 将其复制到您自己的不会被覆盖的字符串中。

这是解决该问题的另一个答案:Saving new points in time with ctime overwrites the old strings?