所以我有以下代码,我想做的简化版本.我有一个带有成员变量的类,我希望将其设置为潜在的各种不同的数据类型,具体取决于具体情况(我只是为此测试制作了一个随机结构).我不断在memcpy函数上遇到seg错误,我不明白为什么.
#include <cstdlib>
#include <iostream>
#include <assert.h>
#include <string>
#include <string.h>
#include <stdio.h>
using namespace std;
struct product
{
int price;
string name;
};
class object
{
public:
void setData(void *ptr);
void* data;
};
void object::setData(void *ptr)
{
assert(ptr);
memcpy(data, ptr, sizeof(ptr));
}
int main()
{
product* bag;
product ba;
bag = &ba;
bag->price = 5;
bag->name = "bag";
object test;
test.setData(bag);
cout<<test.data->name<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud) 所以我知道以下代码可以使用'='并且更容易和更好,但我正在尝试更好地理解memcpy以用于更复杂的应用程序.当我使用"ptr = b"时,我得到"1"的输出,这是我所期望的.在使用memcpy时,会出现段错误.
#include <string.h>
#include <iostream>
using namespace std;
int main()
{
int a = 1;
int *b = &a;
void* ptr;
memcpy(ptr, b, sizeof(b));
int *c = (int *)ptr;
cout<<*c<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud) 所以我有以下两种结构.假设我有一个无效指针,根据情况,指向包或苹果.如何检查它指向哪种结构类型,以便我可以取消引用它?
struct product
{
int price;
string name;
};
struct fruit : product
{
int weight;
};
product bag;
fruit apple;
Run Code Online (Sandbox Code Playgroud)
编辑:所以这只是我在新工作中使用的代码的简化版本.我需要检查一个特定的变量,但是像水果中的权重变量一样,有时它会被一个空指针传递,有时它不是.已经有很多代码,所以从void指针改变它会太多了.我需要检查权重变量是否存在,然后根据其中的值做一些事情.