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

 

原文链接: https://www.cnblogs.com/Fred1987/p/15766171.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    c struct with char array property

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/401635

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月19日 上午9:19
下一篇 2023年4月19日 上午9:19

相关推荐