Can you see anything wrong?

Started by
1 comment, last by CoiN 23 years, 7 months ago
Lo All, This program compiles with no errors or warnings, but its still crashes on my computer but it worked on someone else''s.....Can anyone see anything that could cause it too crash, cause it really getting on my nerves now It seems to crash on the second loop of the first nested for loop (inner), when putting the numbers in test.num.
    
#include <iostream>
using namespace std;

class test {
	int num;
public:
	void setnum(int n) { num = n; cout << "Test! " << n; }
	int shownum() { return num; }
};

int main()

{
	test tester[5][5], **p;
	int inner, outer;

	p = (test **) tester;

	for (outer=0; outer<5; outer++)
		for (inner=0; inner<5; inner++)
		{
			p[outer][inner].setnum(outer+inner);
		}

	for (outer=0; outer<5; outer++)
		for (inner=0; inner<5; inner++)
		{
			cout << p[outer][inner].shownum() << "\n";
		}

	return 0;
}
    
Thanks in Advance.....
Advertisement
Your problem is this:

p = (test **) tester;

That is wrong. You can cast freely between pointers and 1-d arrays, but definately NOT 2-d or higher. You should instead add an operator[] to your class test and declare "p" as a test*. There may be other ways but that''s probably how I would do it.

Your problem is that a double pointer isn't the proper way to get access to a two-dimensional array, as the anonymous poster said. There's two very easy ways to fix this: You could either just index tester instead of p, as in tester[outer][inner].setnum(), or if you want to use pointers, then use some pointer math for the loops:

#include using namespace std;    class test {        int num;    public:        void setnum(int n) { num = n; cout << "Test! " << n; }        int getnum() { return num; }};int main() {    test tester[5][5], *p;    int inner, outer;		    for (outer = 0, p = (test *) tester; outer < 5; outer++)        for (inner = 0; inner < 5; inner++, p++) {            p->setnum(outer+inner);        }    for (outer = 0, p = (test *) tester; outer < 5; outer++)        for (inner = 0; inner < 5; inner++, p++){            cout << p->getnum() << "\n";        }    return 0;} 


this works because of the way two-dimensional arrays are stored linearly in memory.


Edited by - random-nomad on August 29, 2000 3:37:39 PM

This topic is closed to new replies.

Advertisement