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

时间:2015-05-04 18:49:02

标签: c++ visual-c++

当我运行代码时,指针被破坏

#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;
    }
}

根据视觉工作室直到最后它没有变得腐败,我使用指针错了吗?

1 个答案:

答案 0 :(得分:1)

One issue is here:

    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
    }

Your finger array is declared as having cols number of entries, but your loop access finger using count, which will exceed the cols value. In other words, you declared your fingers array with a certain size, but when you start to do things with it, you do not respect the boundaries of the fingers array.

The fix is to make sure you never go past the end of the fingers array, or if the intent was to make fingers have numberCount elements, then use std::vector:

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

Then the code stays the same and will not crash. Whether the results are what you're looking for in terms of having sorted numbers, that's another story. But your code will not crash if you make these changes.