C++ get struct array via pointer and struct has char * properties

#include <iostream>
#include <uuid/uuid.h>
#include <ctime>
#include <string.h>

using namespace std;

static char* dtValue=(char*)malloc(20);
static char* uuidValue=(char*)malloc(40);
char *getUuidValue1();
struct BookStruct
{
    unsigned long long BookId;
    char * BookName;
    char * BookTitle;
};

void getStructArray(struct BookStruct *ptr,int len);
void structArray3();

int main()
{
    structArray3();
    return 0;
}

void structArray3()
{
    int len=10000;
    struct BookStruct arr[len];
    getStructArray(arr,len);
    for(int i=0;i<len;i++)
    {
        cout<<"Index="<<i+1<<",Id="<<arr[i].BookId<<",Name="<<arr[i].BookName<<",Title="<<arr[i].BookTitle<<endl;
        free(arr[i].BookName);
        free(arr[i].BookTitle);
    }
    cout<<"Finished in structArray3()"<<endl;
    free(uuidValue);
}

void getStructArray(struct BookStruct *ptr,int len)
{
    for(int i=0;i<len;i++)
    {
        ptr->BookId=(unsigned long long)i*i*i*i;
        ptr->BookName=(char*)malloc(40);
        ptr->BookTitle=(char*)malloc(40);
        strcpy(ptr->BookName,getUuidValue1());
        strcpy(ptr->BookTitle,getUuidValue1());
        ptr++;
    }
}

char *getUuidValue1()
{
    uuid_t newUUID;
    uuid_generate(newUUID);
    uuid_unparse(newUUID,uuidValue);
    return uuidValue;
}

Compile

g++ -g -std=c++2a -I. h1.cpp -o h1 -luuid

Run ./h1

 

posted @ 2022-01-11 09:04  FredGrit  阅读(41)  评论(0编辑  收藏  举报