gpt4 book ai didi

c++ - 是否可以将指向已知大小的连续内存的指针转换为结构?

转载 作者:行者123 更新时间:2023-11-28 06:19:46 25 4
gpt4 key购买 nike

例如

int pages[3];
int *page_ptr;
page_ptr = pages;

//

test a;
*page_pointer = a;

我想获取一个与pages 大小相同的结构(test),并将其放置在pages 的内存位置。这可能吗?

  • 无需更改页面上的数据,只需更改页面的访问方式即可。

最佳答案

I want to take a structure (test) of same size as pages and place it at the memory location of pages. Is this possible?

是的,这是可能的。但是,而不是使用

*page_pointer = a; 

你应该使用memcpy

memcpy(page_pointer, &a, sizeof(pages));

更新,回应 OP 的评论

我想你是在问你是否可以做这样的事情:

#include <iostream>

struct foo
{
int a;
int b;
int c;
};

int main()
{
int array[3] = {10, 20, 30};
foo* ptr = static_cast<foo*>((void*)array);
std::cout << ptr->a << ", " << ptr->b << ", " << ptr->c << std::endl;
}

我在 g++ 4.9.2 上试过了,运行正常。我不确定它是否违反任何类型别名规则。

关于c++ - 是否可以将指向已知大小的连续内存的指针转换为结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29522368/

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