将指针转换为结构 [英] Converting Pointer to a Struct

查看:98
本文介绍了将指针转换为结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道将指向值数组的指针转换为指向结构的指针的有效方法是什么。是否需要深层复制?什么是更好的解决方案?

I was wondering what is an efficient way of turning a pointer to an array of values to a pointer to a struct. Would deep copy be necessary? What's the better solution?

struct Frame
{
	BYTE bof;
	WORD type;
	BYTE frameNum;
	BYTE numFrames;
	BYTE dataSize;
};


void main()
{
	BYTE* list = new BYTE[7]; 
	list[0] = 1;
	list[1] = 0xFF;
	list[2] = 0xFF;
	list[3] = 4;
	list[4] = 5;
	list[5] = 6;
	list[6] = 7;
	Frame* pFrame = (Frame*)(list);
	delete[] list;
}

推荐答案

怎么样:

Frame *ptr = new Frame;

ptr-> bof = ....

ptr->bof = ....

删除ptr;

但是有两个陷阱:

1。对准。 Frame.type是一个WORD,所以填充通常会在bof之后添加。要解决此问题,请使用

pragma pack

1. Alignment. Frame.type is a WORD, so padding will be normally added after bof. To workaround this, use pragma pack.

2。而不是裸露的新&删除,使用现代C ++智能指针(高级)。

2. Instead of bare new & delete, use the modern C++ smart pointers (advanced).

- pa


这篇关于将指针转换为结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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