#include <iostream> #include <uuid/uuid.h> #include <ctime> #include <random> #include <unistd.h> #include <string.h> #include <exception> #include <typeinfo> #include <stdexcept> using namespace std; static char *dtValue = (char *)malloc(20); static char *uuidValue = (char *)malloc(40); char *getTimeNow(); char *getUuidValue3(); struct BookStruct2 { unsigned long long BookId; char *BookName; char *BookTitle; }; void getStructArray9(struct BookStruct2 *ptr, int len); void printBookStruct10(); int main() { printBookStruct10(); return 0; } void printBookStruct10() { int len = 10000; struct BookStruct2 arr[len]; getStructArray9(arr, len); for (int i = 0; i < len; i++) { cout << "Index=" << i << ",Id=" << arr[i].BookId << ",name=" << arr[i].BookName << ",title=" << arr[i].BookTitle << endl; } cout << "Finished in structArray7() and now is " << getTimeNow() << endl; free(dtValue); free(uuidValue); } void getStructArray9(struct BookStruct2 *ptr, int len) { for (int i = 0; i < len; i++) { ptr->BookId = (unsigned long long)i * i * i; ptr->BookName = (char *)malloc(40); strcpy(ptr->BookName,getUuidValue3()); ptr->BookTitle = (char *)malloc(40); strcpy(ptr->BookTitle,getUuidValue3()); ptr++; } } char *getUuidValue3() { uuid_t newUUID; uuid_generate(newUUID); uuid_unparse(newUUID, uuidValue); return uuidValue; } char *getTimeNow() { time_t rawTime = time(NULL); struct tm tmInfo = *localtime(&rawTime); strftime(dtValue, 20, "%Y%m%d%H%M%S", &tmInfo); return dtValue; }
Pay attention to the char *BookName in struct BookStruct,when assign the retrieved uuid value to the struct char *BookName
At first,allocate memory to the char * BookName
ptr->BookName = (char *)malloc(40);
Then assign the retrieved uuid value dynamically by computer via strcpy method instead of = directly
strcpy(ptr->BookName,getUuidValue3());
Compile via
g++ -g -std=c++2a -I. h1.cpp -o h1 -luuid
Run ./h1