1

在下面的程序中,当程序进入 while 循环时,它停止工作。当我尝试在没有循环的情况下分配值时,它醒了。谁能告诉我问题是什么?我正在使用 Visual Studio 2010。

#include <stdio.h>
#include<iostream.h>
#include <conio.h>

using namespace std;
int random(int min,int max);

struct pts
{
    int x;
    int y;
};

int main()
{
    struct pts *p;
    int w = 600,h=400;
    int nmax,kmax,k=0,n=0;

    while(k<5)
    { 
        p[0].x = random(0,h-1);
        p[1].y = random(0,w-1);
        cout << p[0].x << "   " << p[1].y << "\n";
        k++;
     }
     getch();
     return 0;
}

int random(int min,int max)
{
    int n=0;
    n=(rand()%(max-min+1))+min;
    return n;
}
4

1 回答 1

2

while循环本身工作正常。只是你在破坏记忆。你的问题是:

struct pts *p;
p[0].x = whatever;

p没有对有效内存块的干预设置。换句话说,您正在使用一个未定义的指针,因此是未定义的行为,因此所有的赌注都是关闭的。

由于您(当前)似乎只使用p[0]and p[1],您可能可以更改:

struct pts *p;

到:

struct pts p[2];

当然,如果你想要一个可变结构,你可以使用:

struct pts *p = new pts[500];

当然,用你想要的任何大小替换 500。


You might also want to consider upgrading to a more recent compiler, iostream.h and conio.h are anachronisms.

Here's a complete program that shows how to do it, at least until you decide to store things a little more "sanely" inside the loop:

#include <iostream>
#include <stdlib.h>

struct pts
{
    int x;
    int y;
};

int random(int min,int max)
{
    int n=0;
    n=(rand()%(max-min+1))+min;
    return n;
}

int main()
{
    struct pts p[2];
    int w = 600,h=400;
    int k=0;

    while(k<5)
    {
        p[0].x = random(0,h-1);
        p[1].y = random(0,w-1);
        std::cout << p[0].x << "   " << p[1].y << "\n";
        k++;
     }
     return 0;
}

A sample run of that gives:

183   286
377   115
193   535
186   492
249   421

(and, in fact, will probably always give that sequence since you don't call srand to set the seed - your numbers may well be different to mine but they'll give you the same sequence every time).


If you want a better baseline to start with, see:

#include <iostream>
#include <stdlib.h>
#include <time.h>

struct pts { int x; int y; };

int random (int min, int max) {
    return (rand() % (max - min + 1)) + min;
}

int main (void) {
    pts *p = new pts[5];
    int w = 600, h = 400;
    int k = 0;

    srand (time (0));
    while (k < 5) {
        p[k].x = random (0, h - 1);
        p[k].y = random (0, w - 1);
        std::cout << p[k].x << "   " << p[k].y << "\n";
        k++;
    }
    delete[] p;
    return 0;
}

This shortens the code a bit by removing unnecessary stuff, and gets rid of your undefined-behaviour problem.

It also initialises the random number generator and populates the array properly.

于 2012-11-03T11:00:39.747 回答