zoukankan      html  css  js  c++  java
  • 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

     

  • 相关阅读:
    IDEA2019破解版安装
    Docker (一)安装与基本命令
    js导出PDF
    python入门笔记一安装
    微信内关闭当前页面
    微信一些网页
    内网穿透工具:钉钉HTTP内网穿透使用详解
    html生成二维码,qr
    IDEA无法正常启动(打不开&报错)
    微信测试号
  • 原文地址:https://www.cnblogs.com/Fred1987/p/15776533.html
Copyright © 2011-2022 走看看