1

I created a function to retrieve date from a esp32 using c++. Buts it's causing a error.

I see dozens of sites and none of solutions worked to me. The code can change to a better practice if you provide it.

the ideia is. create a function to return a DateTime in a char.

void getCurrentDateTime(char **datetime){
  time_t tt = time(NULL);
  data = *gmtime(&tt);
  strftime(datetime, 64, "%m/%d/%Y %H:%M:%S", &data);
}

I call that function this way.

char *datetime; 
getCurrentDateTime(&datetime);  // my function

The code compiles but crash the esp32 device...

I'm in very beginning of c++ code... so i appreciate if you explain and provide a code for function and a how to call it.

3 Answers3

2

You should initialize datetime first, and pass it as char* to the function.

#include <ctime>

void getCurrentDateTime(char* datetime){
    time_t tt = time(NULL);
    tm data = *gmtime(&tt);
    strftime(datetime, 64, "%m/%d/%Y %H:%M:%S", &data);
}

int main() {
    char datetime[64];
    getCurrentDateTime(datetime);
}
VLL
  • 9,634
  • 1
  • 29
  • 54
  • thanks. that's worked. Just for learning purpose, if i don't know the length of the char... can i instance other char inside function with other length? – Eric Torres Jun 13 '19 at 03:21
  • @EricTorres With `strftime()`, you must select some length yourself. But you can use `std::put_time()` instead: https://stackoverflow.com/questions/10289017/how-to-format-date-and-time-string-in-c – VLL Jun 13 '19 at 05:59
0

you need to initialize the dateTime pointer.there is no allocated memory where datetime pointer points to. so when strftime trying to fill it, it crashes. initialize it with some predefined size of memory

char *datetime = new char(80); 
getCurrentDateTime(&datetime);

update: also strftime takes a char* as first parameter , but you are passing char**

zapredelom
  • 1,009
  • 1
  • 11
  • 28
-1
strftime(*datetime, 64, "%m/%d/%Y %H:%M:%S", &data);

Without further testing Id say its because you need to dereference your "reference-pointer".

Your datetime comes in as 'pointer to a char[]' and then youre trying to print to the pointer instead of the char[]

Narase
  • 490
  • 2
  • 12