根据CIN类型插入空隙*?始终获取unsigned_char的访问异常
Inserting into a void* depending on CIN type? Always get access exception for unsigned_char
if(menu_option==1) //INSERT
{
SDI::StoredData* temp = new SDI::StoredData();
int pos = 0;
void* val = 0;
int type = 0;
string input;
std::cout << "tt2.4 Enter what type of data (0 = int, 1 = float, 2 = string): ";
std::cin >> type;
if(type==0)
{
cout << "ntSelect a value to enter: "; cin >> val;
cout <<"ntEnter the position to insert it: "; cin >> pos;
temp->data = val;
}
else
if(type==1)
{
}
else
{
cout << "ntSelect a value to enter: "; cin >> input;
//std::string *g = (std::string*)p;
//std::string dd = *g;
cout<<"ntEnter the position to insert it: "; cin >> pos;
}
temp->compareValue = 0;
void *vp = static_cast<void*>(new std::string(input));
temp->data = &vp;
temp->type = type;
ARR.insert (temp,pos,true);
arrPos++;
}
拼命尝试插入到我的 void* 指针数组中,与 INT 值完美配合,但是一旦我尝试指定不同类型的数组,例如字符串,我就会尝试将输入字符串转换为 void 指针并将其传递到结构中,这在调试时似乎有效,但是, 一旦我尝试输出列表,我就会得到一个异常unsigned_char并且似乎是 NULL?
for(int i = 0; i<max; i++)
{
if(data[i].data!= nullptr)
{
switch(data[i].type)
{
case 0:
{
int *p = (int*)data[i].data;
std::cout<<"("<<i<<")"<<*p<<" => ";
logger.Log(1,"Data is of INT type","Array::getAllValues()");
break;
}
case 1:
{
float *p = (float*)data[i].data;
std::cout<<"("<<i<<")"<<*p<<" => ";
logger.Log(1,"Data is of FLOAT type","Array::getAllValues()");
break;
}
case 2:
{
std::string *p = (std::string*)data[i].data;
std::cout<<"("<<i<<")"<<*p<<" => ";
logger.Log(1,"Data is of STRING type","Array::getAllValues()");
break;
}
default:
break;
}
logger.Log(1,"Data isnt null, printing value","Array::getAllValues()");
}
else
{
logger.Log(1,"value is null, printing NULL=>","Array::getAllValues()");
std::cout<<"("<<i<<")"<<"NULL"<<" => ";
}
}
你的直接问题是这些行。
void *vp = static_cast<void*>(new std::string(input));
temp->data = &vp;
您将局部变量的地址存储在某个地方,以便稍后使用它。
但是这段代码还有其他几个严重的问题。
例如
cout << "ntSelect a value to enter: ";
cin >> val;
请参考一些关于C++的好书,并尽量避免指针。如有必要,请使用现代智能指针。
相关文章:
- C++为构建时间获取QDateTime的可靠方法
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 使用指针从C++中的数组中获取最大值
- 如何获取std::result_of函数的返回类型
- 如何在openssl-ecc中获取十六进制格式的私钥
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 使用Unreal C++获取VR耳机的世界位置/方向
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 从C字符串中获取奇怪的字符串长度
- 为什么我的for循环不能正确获取argv
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 从python中调用C++函数并获取返回值
- 如何获取一个数字的前3位
- 获取字符串的长度并将其分配给数组
- 无法获取菜单选择以运行函数.C++
- 数组长度,为什么从命令行获取时不能使用它?
- Boost Spirit,获取迭代器内部语义动作
- 尝试通过OCI例程从Oracle获取blob数据,但出现错误:ORA-01008:并非所有变量都绑定
- 在unsigned int var中获取负值