在创建predefined结构动态矢量 [英] Creating dynamic vector on predefined struct

查看:121
本文介绍了在创建predefined结构动态矢量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个predefined结构的使用方法:

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;

它包含联盟,以减少内存使用情况。
我所知道的大小可以有所不同,因为M32 M64和汇编(指针大小)。
我的问题是如何使用该结构为我的precise分配。这个结构的目的是实现基本的位操作,​​s变量包含以字节为位图的大小。如果位图可以容纳的指针所占用的位图,则我们分配了内存有里面。我写了一些位图操作就可以了,但我不能真正得到结构或如何操作就可以了。

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.

推荐答案

我不明白你的问题是什么。你必须有一个主要功能,将根据指针大小正确的指针返回位图:

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

所有其他功能必须使用此功能以获得正确的指针位图。还需要构造函数/析构函数对初始化/正确的方式取消初始化位图指针(原因我显示最简单的例子假设你有null结尾的位图):

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

这篇关于在创建predefined结构动态矢量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆