Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        2年前关闭。
                                                                                            
                
        
我正在为一个类做一个项目(已经提交),但是初始化int 2D动态数组时的读取访问冲突仍然困扰着我,我不知道是什么原因引起的。

class kMeans
{
public:
    //xyCoord struct
    struct xyCoord
    {
        int Label;
        int xCoordinate;
        int yCoordinate;
    };

    //variables
    int K;
    xyCoord *Kcentroids;
    int numPts;
    aPoint *pointSet;
    int numRow;
    int numCol;
    int **imageArray = NULL;
    int changeLabel;

    //constructor
    kMeans(int clusterNum, int numPoints, int row, int col)
    {
        //initializes the row and column values
        numCol = col;
        numRow = row;

        //Allocate the row and column as the size of the 2D array
        imageArray = new int*[row];
        for (int i = 0; i < row; i++)
        {
            imageArray[i] = new int[col];
        }

        //initializes the 2D array to contain all 0s
        for (int i = 0; i < row - 1; i++)
        {
            for (int j = 0; i < col - 1; j++)
            {
                imageArray[i][j] = 0;   //read access violation occurs here
            }
        }

        //Allocate numPoints as the size of the array
        pointSet = new aPoint[numPoints];
        numPts = numPoints;

        //Allocate clusterNum as the size of the array
        Kcentroids = new xyCoord[clusterNum];
        K = clusterNum;

        //Initialize the labels for each Kcenteroid
        for (int i = 0; i < K; i++)
        {
            Kcentroids[i].Label = i + 1;
        }
    }


该错误以前没有出现过,但是当我决定在提交之前再次运行该程序时,出现了读取访问冲突,所以我不确定是什么原因引起的。

最佳答案

更改此:

for (int j = 0; i < col - 1; j++)


对此:

for (int j = 0; j < col - 1; j++)


因为您要检查j而不是i的条件。

关于c++ - 初始化二维动态数组C++时发生读取访问冲突,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46852796/

10-14 11:06