Solved

C++, array of pointers to objects

Posted on 2013-01-22
1
233 Views
Last Modified: 2013-01-22
Hello experts, please have a look at the code below:

#include <iostream>
using namespace std;

class Dog{
public:
	int x;

};

int main(){
	Dog * matrix[12];
	int * matrixInt[12];

	*matrixInt[0] = 12; //works fine
	*matrix[0]->x = 12; //does not work

	return 0;
}

Open in new window


How can I make it work?
Thank you

panJames
0
Comment
Question by:panJames
1 Comment
 
LVL 30

Accepted Solution

by:
Zoppo earned 500 total points
ID: 38804963
Hi panJames,

you're declaring array to pointers, but the pointers are uninitialized. You need to allocate memory for them, i.e.:
Dog* matrix[12];
for ( int i = 0; i < 12; i++ )
{
 matrix[i] = new Dog;
}
...
// need to clean up when you don't need it anymore.
for ( int i = 0; i < 12; i++ )
{
 delete matrix[i];
}

Open in new window

(do it similar for the matrixInt)

Hope this helps,

ZOPPO
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now