5

I have variable tmit: long tmit;. I got error in this code:

printf("Time: %s",ctime(&tmit));

And error say: Cannot convert 'long int*' to 'const time_t* {aka const long long int*}' for argument '1' to 'char* ctime(const time_t*)' My question is, how convert long to time_t without lossing any information about time or how change this code, if I like to see date. I working on this answer, but I got error.

Community
  • 1
  • 1
Nejc Galof
  • 2,538
  • 3
  • 31
  • 70
  • Note that the exact type of `time_t`, and its semantic meaning, is specified by the language standard to be "implementation defined". It could be a `long long` holding seconds since 1970-01-01, or a double holding seconds since 1900-01-01, or... you get the idea. – DevSolar Apr 12 '16 at 14:43

2 Answers2

7

In general, you can't as there need not be any reasonable connection between std::time_t and an integer like long.

On your specific system, std::time_t is a long long, so you can just do

std::time_t temp = tmit;

and then use temp's address. Note that this need not be portable across compilers or compiler versions (though I would not expect the latter to break).

It is worth checking whether whatever is saved in tmit gets interpreted by functions like ctime in a sensible way, as you did not tell us where that came from.

Depending on how this tmit is produced, it might also be a good idea to use an std::time_t tmit instead of long tmit from the get go and thus eliminate this conversion question entirely.

If you don't have to use the old C-style time facilities, check out the C++11 <chrono> header.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
4

You cannot simply "convert" one type of pointer to a pointer to an incompatible object type.

What you want to do, is to create an object of that another type, then initialize it using the impicit conversion between the object types, and finally pass a pointer to the newly created object:

std::time_t t = tmit;
ctime(&t);
eerorika
  • 232,697
  • 12
  • 197
  • 326