簡體   English   中英

c++ operator* 拋出“讀取訪問沖突”錯誤

[英]c++ operator* throws a "read access violation" error

我正在嘗試創建一個 Vector3 結構,但每次我使用運算符 * 時,它似乎都會拋出異常“讀取訪問沖突”。 我是 C++ 的新手,不知道是什么原因造成的。 VS 2017,調試,x86

代碼

    float x, y, z;

    Vec3 operator+(Vec3 d) {
        return { x + d.x, y + d.y, z + d.z };
    }
    Vec3 operator-(Vec3 d) {
        return { x - d.x, y - d.y, z - d.z };
    }
    Vec3 operator*(float d) {
        return { x * d, y * d, z * d }; // throwing an exception
        /*
        Unhandled exception thrown: read access violation.
        this was 0x302C.*/
    }

    void Normalize() {
        while (y < -180) {
            y += 360;
        };
        while (y > 180) {
            y -= 360;
        };
        if (x > 89) {
            x = 89;
        };
        if (x < -89) {
            x = -89;
        };
    }
};
// example code
uintptr_t c= *(uintptr_t*)(ModuleHandle+ 0x2);
Vec3* b= (Vec3*)(c+ 0x1); 
Vec3 a= *b* 2;

你在b之前有一顆星:

Vec3 a= *b* 2;

編輯關於已編​​輯的問題,上面的另一行代碼現在似乎是問題:

Vec3* b= (Vec3*)(c+ 0x1); 

如果c不是至少 2 個正確初始化的Vec3實例的數組,則取消引用將導致您看到的訪問沖突。

我的意思是字面上的Vec3*Vec3[]類型,而不是char*或其他東西。 因為您要給它加 1,所以數組的類型必須是單個項目的類型,以便 CPU 知道將指針向前移動多少。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM