array returned by function causing malloc error?

I read a thread on here, I don't remember which but that you can pass an array from a function, in retrospect I should've just rewrote the function so this isn't an issue but whatever. code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
unsigned long* collisionhandler::checkpellethit(int good, int *n)
{
	printf("In collisionhandler, checkpellethit\n");
	*n = 0;
	int q = weapons.size();
	weapon w;
	unsigned long *dead = new unsigned long[q];
	for (int i=0;i<q;i++)
	{
		printf("In collisionhandler, checkpellethit, outer for loop\n");
		w = weapons[0];
		weapons.erase(weapons.begin());
		if(w.type==3)
		{
			int r = players.size();
			int killed = 0;
			for (int j=0;j<r;j++)
			{
				printf("In collisionhandler, checkpellethit, inner for loop\n");
				if(players[j].good!=good)
				{
					playerarea[!good]->setarea(players[j].x,players[j].y,players[j].theta);
					shotguns[good]->setarea(w.x,w.y,w.theta);
					if (playerarea[!good]->didhit(*shotguns[good]))
					{
						printf("In collisionhandler, checkpellethit, inner if statement, read true (hit)\n");
						killed=1;
						dead[*n]=w.idd;
						player a = players[j];
						players.erase(players.begin()+j);
						a.hit=1;
						players.push_back(a);
						*n++;
					}
				}
			}
			if(!killed)
			{
				weapons.push_back(w);
			}
		}
		else 
		{
			weapons.push_back(w);
		}
	}
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
void shotgun::checkhit()
{
	printf("in shotgun, checkhit\n");
	int h = shots.size();
	vector<struct bb> b;
	struct bb f;
	int numhit=0;
	unsigned long *dead = c->checkpellethit(good,&numhit);
	for(int i=0;i<h;i++)
	{
		printf("in for loop\n");
		b = shots[0];
		shots.erase(shots.begin());
		int h=b.size();
		for(int j=0;j<h;j++)
		{
			int k=0;
			int done=0;
			while((k<numhit)&&!done)
			{
				fprintf(stdout,"Check: b[j].idd: %lu dead[k]: %lu\n",b[j].idd,dead[k]);
				if(b[j].idd==dead[k])
				{
					b.erase(b.begin()+j);
					done=1;
				}
				k++;
			}
		}
		shots.push_back(b);
	}
	delete [] dead;
}
OK this is the same topic as your earlier thread. Keep the same thread going, if you have any more questions
ok got it missing a return statement.

Now it crashes at dead[*n] = w.idd;

gotta figure that one out.
Are you sure the biggest number in n is less than q? Seems like going out of scope to me. Plus I'm assuming you want to return dead.
Last edited on
ne555 figured it out in the other thread. sorry for duplicate thread
Topic archived. No new replies allowed.