【问题标题】:My pointer becomes corrupted and i have no idea why我的指针损坏了,我不知道为什么
【发布时间】:2015-05-04 18:49:01
【问题描述】:

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

主要

#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,直到最后它都不会损坏,我是不是用错了指针?

【问题讨论】:

  • 这里input ++;可以大于数组的大小。您覆盖了数组的末尾,破坏了其他变量的值。
  • 我会从标签中删除 c++14。
  • @Evan,你的代码有很多错误,我不明白你在做什么。
  • @Mustafa 很抱歉在我的 C++ 的第一年,只是我们分配的一个项目,我们需要做一个桶排序来重新组织它。
  • @Evan 你可以使用我的指针。:)

标签: c++ visual-c++


【解决方案1】:

这里有一个问题:

    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);

然后代码保持不变,不会崩溃。就排序数字而言,结果是否是您正在寻找的结果,那是另一回事。但是,如果您进行这些更改,您的代码不会崩溃。

【讨论】:

  • 谢谢!这是我因为没有弄清楚这一点而打自己脸的时刻之一。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多