int值从0跳转到32679而不做任何更改

时间:2011-08-20 15:00:28

标签: c++ variables loops int

我有一个非常非常奇怪的问题,我无法弄明白。所以你可以看看,这是我的代码;

point * findLongPaths(point * points, double threshold_distance) {
    int i = 0;
    int pointsAboveThreshold = countPointsAboveThreshold(points, threshold_distance);

    point * pointsByThreshold = new point[sizeof(points)];
    pointValues * pointsToCalculate = new pointValues[pointsAboveThreshold];
    //pointValues pointsToCalculate[pointsAboveThreshold];
    //point orderedPoints[pointsAboveThreshold];

    while (points[i].end != true) {
        point pointOne = points[i];
        point pointTwo = points[i + 1];

        //Check to see if the distance is greater than the threshold, if it is store in an array of pointValues
        double distance = distanceBetweenTwoPoints(pointOne, pointTwo);
        if (distance > threshold_distance) {
            pointsToCalculate[i].originalLocation = i;
            pointsToCalculate[i].distance = distance;
            pointsToCalculate[i].final = pointTwo;

            //If the final point has been calculated, break the loop
            if (pointTwo.end == true) {
                pointsToCalculate[i].end = true;
                break;
            } else {
                pointsToCalculate[i].end = false;
                i++;
            }
        } else if (points[0].end == true || pointsAboveThreshold == 0) {
            //If there is no points above the threshold, return an empty point
            if (points[0].end == true) {
                point emptyPoint;
                emptyPoint.x = 0.0;
                emptyPoint.y = 0.0;
                emptyPoint.end = true;

                pointsByThreshold[0] = emptyPoint;
                return pointsByThreshold;
            }
        }
        i++;
    }
    i = 0;

    //Find the point with the lowest distance
    int locationToStore = 0;

    while (pointsToCalculate[i].end != true) {

我的问题是,i值字面上从0到32679.我最初将它设置为j,所以它使用了与while循环中的一个不同的计数器,但我尝试使用{{1}看看它是否会有所作为。

我已经在VC ++和XCode中尝试了它,两者都在做。但是,如果我在它之前放置几行断点,它将保持为零。如果我在没有任何断点的情况下运行它,它会将值更改为32679.

这是为什么?这真的很奇怪,我不知道如何解决它?

1 个答案:

答案 0 :(得分:2)

我注意到的一些事情可能有所帮助:

  • new point[sizeof(points)]几乎肯定是错误的,因为sizeof(points)不等于数组中的元素数,而是指针的大小(通常为4或8)。如果您希望points[]的大小将其作为另一个参数传递给函数,或者更好的是,使用标准容器(如std::vector<>或适合您的需要)。
  • 您的pointsToCalculate数组已分配pointsAboveThreshold个元素,但您可以使用i访问它。如果i超过pointsAboveThreshold(几乎肯定会),那么你将会溢出数组并发生不好的事情,包括覆盖i。如果没有更多的信息和细节,我会怀疑这是你的问题。
  • distance > threshold_distancepointTwo.end == false增加i两次时(这可能是有意的,但想要提及它)。
  • else if (points[0].end == true...)永远不会是真的,好像它是外while (points[i].end != true)将是假的并且循环从未进入。我不确定你的预期逻辑,但我怀疑你想要在while循环之外。
相关问题