繁体   English   中英

抛出异常:写访问冲突 C++

[英]Exception thrown: Write access violation C++

我想用数字 2 4 6 8 10 12 14 16 18 20 填充 (obj * m)。在 Microsoft Visual Studio Professional 2019 中,我收到此错误:“抛出异常:写入访问冲突”在“n-> val”行= 数据;" 或第 15 行。但后来我进入 DEV C ++ 应用程序,在那里我意识到错误是什么,由于某种原因,重复开始并且数组普遍恶化,粗略地说,不算初始元素。 通过运行程序,您将自己看到一切,我把它带到那里,一切都清晰可见。

#include <iostream>
using namespace std;
class obj{
public:
    int val, k;
    obj* next;
    obj* n;
    int current = 0;
    
    void func(int data){
        for(n = this, k=0; k<current; n = n->next,k++){
            cout<<"k= "<<k<<" = "<<n<<" = "<<n->val<<" curr= "<< current<<", ";
        }
        cout<<endl;
        n->val = data;
        current++;
    }
    
    void print(){
        for(n =this, k = 0; k<10;n = n->next,k++)
        {
            cout<<n->val<<"  ";     
        }
        
    }
};

int main() {
    obj *m;
    m=new obj [100];
    for(int i=2; i<=20;i+=2)
    {
        m->func(i);
    }
    m->print();
    delete[] m;
    cout << endl;
    return 0;
}

在您的代码中, next未初始化,因此nfunc中的迭代期间变为指向错误的地址

int main() {
    obj *m;
    m = new obj[100];

    /* Initialize `next` */
    for (int i = 1; i < 100; i++)
    {
        m[i - 1].next = &m[i];
    }

    for (int i = 2; i <= 20; i+= 2)
    {
        m->func(i);
    }
    m->print();delete[] m;
    cout << endl;
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM