Eric Torres
Eric Torres

Reputation: 33

c++ modify char inside function

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.

Upvotes: 1

Views: 437

Answers (3)

VLL
VLL

Reputation: 10165

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);
}

Upvotes: 2

zapredelom
zapredelom

Reputation: 1029

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**

Upvotes: 0

Narase
Narase

Reputation: 490

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[]

Upvotes: -1

Related Questions