c struct with char array property
#include <iostream> #include <uuid/uuid.h> #include <ctime> #include <unistd.h> #include <string.h> using namespace std; static char *uuidValue=(char*)malloc(40); static char *dtValue=(char*)malloc(20); char *getTimeNow1(); char *getUuid3(); struct BookStruct { int BookId; char BookName[40]; char BookTitle[40]; }; void printStructArray6(); void getBookStructViaPointer(struct BookStruct *bsP,int i); int main() { printStructArray6(); return 0; } void printStructArray6() { struct BookStruct arr[100]; for(int i=0;i<100;i++) { getBookStructViaPointer(&arr[i],i); cout<<"Index="<<i<<",Id="<<arr[i].BookId<<",Name="<<arr[i].BookName<<",Title="<<arr[i].BookTitle<<endl; } for(int i=0;i<100;i++) { cout<<"Index="<<i<<",Id="<<arr[i].BookId<<",Name="<<arr[i].BookName<<",Title="<<arr[i].BookTitle<<endl; } cout<<"Finished in printStructArray6() and now is "<<getTimeNow1()<<endl; free(dtValue); free(uuidValue); } void getBookStructViaPointer(struct BookStruct *bsP,int i) { bsP->BookId=i*i*i; strcpy(bsP->BookName,getUuid3()); strcpy(bsP->BookTitle,getUuid3()); } char *getUuid3() { uuid_t newUUID; uuid_generate(newUUID); uuid_unparse(newUUID,uuidValue); return uuidValue; } char *getTimeNow1() { time_t rawTime=time(NULL); struct tm tmInfo=*localtime(&rawTime); strftime(dtValue,20,"%Y%m%d%H%M%S",&tmInfo); return dtValue; }
g++ -g -std=c++2a -I. h1.cpp -o h1 -luuid
Run ./h1
Another way is to get array in a batch via pointer and increment pointers
void getBookStructArray8(struct BookStruct *ptr,int len) { for(int i=0;i<100;i++) { ptr->BookId=i*i*i*i; strcpy(ptr->BookName,getUuid3()); strcpy(ptr->BookTitle,getUuid3()); ptr++; } } void printStructArray6() { int len=100; struct BookStruct arr[len]; getBookStructArray8(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 printStructArray6() and now is "<<getTimeNow1()<<endl; free(dtValue); free(uuidValue); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现