如何取消结构的索引
How do you unindex a struct?
如何取消结构索引?例:
typedef struct String_s {
int current_location;
int size;
char data[0];
} String;
char* String_getCString(String *str){
return &str->data[0];
}
//this is supposed to take the result of 'String_getCString' and reverse the process to get the String*
//i.e. String_getCString(CString_getString(str)) == str
String* CString_getString(char *str){
//???
}
int foo(char *cstr){
printf("%sn", cstr);
fflush(0);
free(CString_getString(cstr));
}
int main(int argc, char *argv[]){
const char *hello_world = "hello world";
String *str = (String*)malloc(sizeof(String)+1000*sizeof(char));
str->size = 1000;
str->count = strlen(hello_world);
char *cstr = String_getCString(str);
strcpy(cstr, hello_world);
foo(cstr);
return 0;
}
我不是 100% 确定我理解您希望CString_getString
做什么,但如果您希望它在传递嵌入式data
字段的地址时返回整个String
对象的地址,那么这很简单,但很危险:
#include <stddef.h>
String *CString_getString(char *str)
{
return (String *)(str - offsetof(String, data));
}
如果您希望"取消索引"的字段类型不是[signed/unsigned/] char
,则需要在减法之前将输入指针强制转换为char *
,并在之后强制转换为所需的返回类型。
这很危险,因为CString_getString
无法知道您是否传入了确实是String
对象的嵌入data
字段的str
。 如果你弄错了,C 编译器会坐下来,看着它在运行时爆炸。 但是,可以说,这并不比人们一直在 C 中所做的任何其他事情差,这可能是一种有用的技术。 例如,它在Linux的内脏中被大量使用:http://lxr.free-electrons.com/ident?i=container_of
相关文章:
- 保持排序的数据结构,允许log N插入时间,并且可以返回我在log N中查找的元素的索引
- 获取结构 c++ 中元素的索引
- C++ STL 数据结构常时按索引推送/弹出/随机访问,并具有指向元素的可靠指针
- 如何使用值获取结构的索引
- 如何二进制搜索结构向量并在适当的索引处插入
- 用于存储网格(将具有负索引)的数据结构
- 是否可以将结构分配给向量的索引?
- 在 c++ 中为结构实现索引器
- 查找索引数据结构,例如`sTD :: vector`(非数组)
- 如何对同一数组索引下的结构成员进行排序?
- 从右到左计算当前索引中的数据结构中的元素数,并打印每个元素的计数
- 使用c中的结构的malloc通过大量存储器进行索引
- 尝试将文件读入结构数组,但 for 循环仅显示第一个索引,其余索引显示为零
- 如何创建辅助数据结构来跟踪 c++ 中 decrease_key 操作的堆索引
- C 用于向量中的结构访问索引或使用参考值
- 如何使用索引访问C 结构属性值
- C++ 中结构的动态索引数组
- 当结构数组在主线程中填充数据时,从结构数组的低索引元素读取是否线程安全
- 如何取消结构的索引
- 如何使用位表示访问可索引的数据结构