gpt4 book ai didi

c++ - 如何初始化属于 struct typedef 一部分的数组?

转载 作者:太空狗 更新时间:2023-10-29 23:37:51 25 4
gpt4 key购买 nike

如果我有一个结构体的类型定义

typedef struct 
{
char SmType;
char SRes;
float SParm;
float EParm;
WORD Count;
char Flags;
char unused;
GPOINT2 Nodes[];
} GPATH2;

它包含一个未初始化的数组,我如何创建这种类型的实例,以便在 Nodes[] 中保存 4 个值?

编辑:这属于用汇编程序编写的程序的 API。我想只要内存中的底层数据相同,更改结构定义的答案就会起作用,但如果底层内存不同则不行。汇编语言应用程序不使用此定义....但是....使用它的 C 程序可以创建汇编语言应用程序可以“读取”的 GPATH2 元素。

一旦创建了 GPATH2 的实例,我是否可以调整 Nodes[] 的大小?

注意:我会用一个直接的 C 标签放置它,但只有一个 C++ 标签。

最佳答案

如果你真的想,你可以混合使用 C 和 C++:

#include <new>
#include <cstdlib>

#include "definition_of_GPATH2.h"

using namespace std;

int main(void)
{
int i;
/* Allocate raw memory buffer */
void * raw_buffer = calloc(1, sizeof(GPATH2) + 4 * sizeof(GPOINT2));
/* Initialize struct with placement-new */
GPATH2 * path = new (raw_buffer) GPATH2;

path->Count = 4;
for ( i = 0 ; i < 4 ; i++ )
{
path->Nodes[i].x = rand();
path->Nodes[i].y = rand();
}

/* Resize raw buffer */
raw_buffer = realloc(raw_buffer, sizeof(GPATH2) + 8 * sizeof(GPOINT2));

/* 'path' still points to the old buffer that might have been free'd
* by realloc, so it has to be re-initialized
* realloc copies old memory contents, so I am not certain this would
* work with a proper object that actaully does something in the
* constructor
*/
path = new (raw_buffer) GPATH2;

/* now we can write more elements of array */
path->Count = 5;
path->Nodes[4].x = rand();
path->Nodes[4].y = rand();

/* Because this is allocated with malloc/realloc, free it with free
* rather than delete.
* If 'path' was a proper object rather than a struct, you should
* call the destructor manually first.
*/
free(raw_buffer);

return 0;
}

诚然,它不像其他人观察到的那样是惯用的 C++,但如果该结构是遗留代码的一部分,它可能是最直接的选择。

以上示例程序的正确性仅通过使用结构的虚拟定义的 valgrind 检查,您的里程可能会有所不同。

关于c++ - 如何初始化属于 struct typedef 一部分的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4108574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com