In the program below, when the program goes into the while loop, it stops working. When I tried to assisgn values without the loop, it woked fine.
Can anybody tell me what the problem is?
I am using 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;
}
The
whileloop itself is working fine. It’s just that you’re corrupting memory. Your problem is with:with no intervening setting of
pto a valid memory block. In other words, you are using an unitialised pointer, hence undefined behaviour, hence all bets are off.Since you (currently) only seem to be using
p[0]andp[1], you can probably change:to:
Of course, if you want a variable structure, you can use:
replacing 500 with whatever size you want, of course.
You might also want to consider upgrading to a more recent compiler,
iostream.handconio.hare 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:
A sample run of that gives:
(and, in fact, will probably always give that sequence since you don’t call
srandto 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:
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.