根据CIN类型插入空隙*?始终获取unsigned_char的访问异常

Inserting into a void* depending on CIN type? Always get access exception for unsigned_char

本文关键字:unsigned 获取 char 异常 访问 插入 类型 CIN 根据      更新时间:2023-10-16
    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++的好书,并尽量避免指针。如有必要,请使用现代智能指针。