1

I intended to initialize a pointer to an array of objects of the class 'Port.h'. To do so, first a pointer of type 'Port' is initialized, then the constructor of this class is called for every element of the array.

int main(){
   Port *ports;

   for (int m = 0; m < M; m++){
       // Initialize
       ports[m] = Port(***PARAMETERS***);
       // ...
   }
   // ...
}

I am getting the following error when running the code:

error C4700: uninitialized local variable 'ports' used

3 Answers 3

2

Before you could start loading pointers into your array, you need to initialize the array itself:

Port *ports = new Port[M];

However, your class lacks default constructor, so the above declaration will not work. You could make an array of pointers instead, and use it like this:

Port **ports = new Port*[M];

When you put data into the array of pointers, you need to use operator new:

ports[m] = new Port(***PARAMETERS***);
//         ^^^

Since ports holds pointers now, you need to use pointer syntax to access Port's members:

ports[m]->memberFunction(param1, param2); // Note the use of '->' in place of a dot '.'

Once you are done working with the array, you need to delete the individual Port objects, and then delete[] the ports array to avoid memory leaks:

for (int m = 0 ; m != M ; m++) {
    delete ports[m];
}
delete[] ports;

Note: much code is dedicated to management of memory now. To avoid having to write this code, use standard collections and smart pointers.

Sign up to request clarification or add additional context in comments.

Comments

1

The error message is clear enough: variable ports was not initialized

Port *ports;

So it has any arbitrary value.

You need to allocate memory for the array that you are going to use. For example

Port *ports = new Port[M];

And it would be better if instead of the dynamically allocated array you would use class std::vector. For example

std::vector<Port> ports( M, Port(***PARAMETERS***) );

Comments

1

At the very least, you should allocate a zone for that pointer:

 #define M 15 /* or whatever you want */
 Port *ports = new Port[M];

Don't forget to deletethe array later, perhaps by ending your main with

 delete[] ports;

But I believe you should not use a pointer to an array zone, but a vector, e.g.

 std::vector<Port> ports;

Read more about std::vector. You probably want to call its resize or its push_back or emplace_back methods (assuming C++11). So if you can construct some Port(12,"abc"); you would call:

 ports.emplace_back(12,"abc");

to construct and add such a port at the end of your ports vector.

1 Comment

Thank you for your response, I will consider using vectors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.