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);
}
复制代码

 

posted @   FredGrit  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示