创建具有只是内存位置的动态数组在一个文件中 [英] Creating a dynamic array with only location of memory in a file

查看:113
本文介绍了创建具有只是内存位置的动态数组在一个文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在的文件头后4个字节偏移数组中的布局结构的一些文件* FP标头。

I have some file *fp which has structs laid out in an array at an offset of 4 bytes after the file's header "header."

我将如何使用类型转换来读取内存中仅使用了位置,这个数组的单个结构?

How would I use typecasting to read individual structs out of this array using only the location in memory?

难道是这样呢?

struct_name *arr = (struct_name *) &header + 4; 

struct_name x = arr[1];

我在做类似的东西,但得到分割故障。做任何事情需要在这里的malloc-ED?

I am doing something similar but getting a segmentation fault. Does anything need to be malloc-ed here?

推荐答案

(struct_name *)及。头文件在你的问题意味着从根本上误解

The (struct_name*)&header in your question implies a fundamental misconception.

除非这个变量存储文件的全部数据(而不仅仅是标题),利用其地址可能是一个非常糟糕的主意,因为数据的其余部分是不会来找它。

Unless this variable stores the entire data of the file (and not just the header), using its address is probably a very bad idea, because the rest of the data is not going to "come after it".

所以下面的答案假定您已经将整个文件读入内存由的char *数据

So the answer below assumes that you have read the entire file into memory pointed by char* data.

从理论上说,你可以做这样的事情:

Theoretically, you could do something like this:

element_struct  val;
element_struct* ptr = (element_struct*)(data+sizeof(header_struct)+4);

// Read the n-th element (starting from 0)
val = ptr[n];

然而,这将是可能不安全,由于不对齐存储器访问操作

However, this would be potentially unsafe, due to unaligned memory access operations.

因此​​,这里是做的一个更安全的方式:

Therefore, here is a safer way of doing it:

element_struct val;
char* ptr = data+sizeof(header_struct)+4;

// Read the n-th element (starting from 0)
memcpy(&val,ptr+n*sizeof(element_struct),sizeof(element_struct));


在除了上述,您需要确保填充添加到您的结构由编译器,准确地反映了你的数据在文件中的布局方式。


In addition to the above, you will need to make sure that the padding added to your structures by the compiler, accurately reflects the way in which your data is laid out within the file.

这篇关于创建具有只是内存位置的动态数组在一个文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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