segmentation fault and cout

Hello again,
When I call the method below and try to print out the results I'm getting a segmentation fault, however if I print out the return value before returning it then it all works fine. I've tried using gdb when it fails to check the return value and does point to the correct object, so I don't understand why I'm getting the fault. Could anyone explain why, and possibly what I'm doing wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
polarField* FFM:: getNearestLearntField(vector<Field*> *fields) const
{
	polarField **closest;
	for(unsigned int i=0; i < fields->size(); i++)
	{
		if(fields->at(i)->isLearnt())
		{
			...
			*closest = (polarField*)fields->at(i);
		}
	}
#ifdef DEBUG
	cout << "Returning field: " << **closest << endl;
#endif
	return *closest;
}

Note: 'polarField' extends 'Field'
In this method, I want to ensure that a pointer to the exact object in the original list is returned, rather than a copy of it.
Many thanks in advance.
Last edited on
My guess is that you're getting a segmentation fault because when you assign the pointer to *closest, you haven't initialized **closest.

I think you should try to change closest to be a pointer and not to a pointer to a pointer. Then make sure you change all relating pointer syntax of course.
Thanks Kooth. I'm still trying to get to grips with pointers, so guess I over did it. Seems to work now though, so thank you.
Anytime, my friend!
Topic archived. No new replies allowed.