我的指针损坏了,我不知道为什么

My pointer becomes corrupted and i have no idea why

当我 运行 我的代码指针损坏时

主要

#include <iomanip>
#include <iostream>
#include "Bucket.h"
using namespace std;

int main()
{
    const int numberCount = 11;

    int startingNumbers[numberCount] = { 100, 79, 255, 355, 70, 85, 10, 5, 47, 62, 75 };

    cout << "Initial Numbers" << endl;
    for (int count = 0; count < numberCount; count++)
    {
        cout << startingNumbers[count] << " ";
    }
    cout << endl;


    bucketSort(startingNumbers, numberCount);

    system("pause");
}

Bucket.h

void bucketSort (int startingNumbers[], int numberCount);

Bucket.cpp

#include <iostream>
#include "Bucket.h"
using namespace std;


void bucketSort(int startingNumbers[], int numberCount)
{
    const int cols = 10;
    const int rows = 11;

    int row = 0;
    int input = 0;

    int *finger[cols];

    int table[rows][cols];

    for (int count = 0; count < numberCount; count++)
    {
        row = startingNumbers[count] % 10;
        table[row][count] = startingNumbers[count];

        finger[count] = &table[row][count];
    }

    for (int count = 0; count < numberCount; count++)
    {
        for (int col = 0; col < cols + 1; col++)
        {
            if (table[count][col] == *finger[col])
            {
                startingNumbers[input] = *finger[col];
                input++;
            }
        }
    }
    for (int count = 0; count < numberCount; count++)
    {
        cout << startingNumbers[count] << endl;
    }
}

根据visual studio直到最后都没有损坏,我是不是指针用错了?

这里有一个问题:

    const int cols = 10;
    //...
    int *finger[cols];
    //...
    for (int count = 0; count < numberCount; count++)
    {
        row = startingNumbers[count] % 10;
        table[row][count] = startingNumbers[count];
        finger[count] = &table[row][count];  // <---- Issue Here
    }

您的 finger 数组被声明为具有 cols 个条目,但是您的循环访问 finger 使用 count,这将超过 cols价值。换句话说,您声明了具有一定大小的 fingers 数组,但是当您开始使用它时,您不遵守 fingers 数组的边界。

解决方法是确保您永远不会越过 fingers 数组的末尾,或者如果意图是使 fingers 具有 numberCount 个元素,则使用 std::vector:

#include <vector>
//...
std::vector<int *> fingers(numberCount);

然后代码保持不变,不会崩溃。就排序数字而言,结果是否符合您的要求,那是另一回事了。但是如果您进行这些更改,您的代码将不会崩溃。