Solved

C++, array of pointers to objects

Posted on 2013-01-22
1
244 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
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.

738 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