You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中用双指针访问类成员二维vector时出现越界错误

Using Double Pointers to Access a 2D Vector Member in a Custom Class

Hey there! I totally get being stuck on a problem even after days of digging—let’s work through this together. Since your legacy codebase forces you to use pointers instead of templates, here’s a practical, pointer-based approach to access your initialized 2D vector member.

First, Let’s Define a Sample Class Structure

I’ll start with a typical class setup matching your description, where the 2D vector is initialized during instantiation:

#include <vector>
#include <iostream>

class CustomClass {
private:
    std::vector<std::vector<int>> m_2DVector; // Your 2D vector member

public:
    // Constructor initializes the 2D vector with fixed dimensions
    CustomClass(size_t rows, size_t cols) {
        m_2DVector.resize(rows, std::vector<int>(cols, 0));
        
        // Optional: Populate with sample data for testing
        for (size_t i = 0; i < rows; ++i) {
            for (size_t j = 0; j < cols; ++j) {
                m_2DVector[i][j] = static_cast<int>(i * cols + j);
            }
        }
    }
};

How to Get a Double Pointer to the 2D Vector

A 2D vector doesn’t directly map to a T** because its rows (sub-vectors) aren’t guaranteed to be stored contiguously in memory. Instead, we’ll create an array of pointers, where each pointer points to the start of a row in the vector.

Add this member function to your class to generate the double pointer:

// Returns a double pointer to the 2D vector's data
int** get2DVectorPtr() {
    // Allocate an array of pointers (one per row)
    int** rowPtrs = new int*[m_2DVector.size()];
    
    // Assign each pointer to the start of its respective row
    for (size_t i = 0; i < m_2DVector.size(); ++i) {
        rowPtrs[i] = m_2DVector[i].data();
    }
    
    return rowPtrs;
}

Using the Double Pointer

Once you have the double pointer, you can use it just like a regular 2D C-style array. Important: Don’t forget to free the allocated pointer array when you’re done to avoid memory leaks!

int main() {
    // Instantiate your class with a 3x4 2D vector
    CustomClass myObj(3, 4);
    
    // Get the double pointer
    int** doublePtr = myObj.get2DVectorPtr();
    
    // Access and print the data
    for (size_t i = 0; i < 3; ++i) {
        for (size_t j = 0; j < 4; ++j) {
            std::cout << doublePtr[i][j] << " ";
        }
        std::cout << "\n";
    }
    
    // Clean up the pointer array
    delete[] doublePtr;
    
    return 0;
}

Key Notes to Avoid Issues

  • No Resizing After Initialization: If your code ever resizes the 2D vector (e.g., push_back on rows or columns), the double pointer will become invalid—since vector resizing can reallocate memory, changing the addresses of rows. Since you mentioned the vector is initialized at instantiation, this shouldn’t be a problem.
  • Const-Correct Version: If you need to access the vector in a const context, use this variant of the function:
    const int** get2DVectorPtr() const {
        const int** rowPtrs = new const int*[m_2DVector.size()];
        for (size_t i = 0; i < m_2DVector.size(); ++i) {
            rowPtrs[i] = m_2DVector[i].data();
        }
        return rowPtrs;
    }
    

This approach fits within your codebase constraints, uses only pointers, and works with your pre-initialized 2D vector.

内容的提问来源于stack exchange,提问作者Zach Stamler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:35:54