Creating dynamic vector on predefined struct

自闭症网瘾萝莉.ら 提交于 2019-12-24 10:59:47

问题


I have a predefined struct to use :

typedef struct somestruct_s {
    int s;
    union {
        unsigned char *ptr;
        unsigned char l_ptr[sizeof(char *)];
    };
}somestruct_t, *somestruct;

It contains union to reduce memory usage. I know the size can vary due to m32 and m64 compilation (pointer size). My question is how to "use" that struct for my precise assignment. The purpose of this struct is to implement basic bit operations, the s variable contains the size of the bitmap in bytes. If the bitmap can fit inside of memory occupied by pointer to bitmap then we allocate her there. Im writing some bitmap operations on it, but i can't really get the struct or how to operate on it.


回答1:


I cannot understand what your problem is. You have to have one major function which will return correct pointer to bitmap depending on pointer size:

unsigned char* somestruct_get_bitmap(somestruct_t* ths) {
    if( sizeof(char*) > ths->s ) 
        return ths->ptr;
    return ths->l_ptr;
}

all other functions must use this function to get the correct pointer to bitmap. Also you need the constructor/destructor pair to initialize/deinitialize bitmap pointer in the correct way (of cause I am showing the simplest example supposing that you have null-terminated bitmaps):

unsigned char* somestruct_init(somestruct_t* ths, unsigned char* ptr) {
    ths->s = strlen(ptr) + 1;
    if( sizeof(char*) > ths->s )  {
       ths->ptr = strdup(ptr);
       return;
    }
    strcpy(ths->l_ptr, ptr);
}

unsigned char* somestruct_destroy(somestruct_t* ths) {
    if( sizeof(char*) > ths->s )  {
        free(ths->ptr);
        return;
    }
}


来源:https://stackoverflow.com/questions/15616103/creating-dynamic-vector-on-predefined-struct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!