C++ struct array with char * properties,convert int to unsigned long long
#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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现