Solved

C++, array of pointers to objects

Posted on 2013-01-22
1
241 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 31

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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

740 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