Question:
What's a proper way to initializeand use an array of pointes to a struct in c++?
anonymous
2010-11-05 17:35:14 UTC
I think I just killed my computer with memory leaks.
what's a proper way to initialize an array (fixed size)of pointes to a structure
Four answers:
MichaelInScarborough
2010-11-05 19:17:31 UTC
The following code has a struct encapsulating an int.

By default the int value is initialized to 0, or if a different

value is passed to that different value;

main declares an array of pointers to A (p) as well as an A array (b).

this code makes the pointer array elements to point to the elements of the b array.

for (int i = 0; i < 5; i++) {

p[i] = &b[i];



And finally this code outputs the elements of the b array using pointers:

for (int i = 0; i < 5; i++) {

cout << "p[" << i << "]->a: " << p[i]->a << " b[" << i << "].a : " << b[i].a << "\n";

}





#include "stdafx.h"

#include

using namespace std;

struct A{

A() : a(0){}

A(int iNo) : a(iNo) {}

int a;

};

int main (){

A *p[5];

A b[] ={1,2,3,4,5};

for (int i = 0; i < 5; i++) {

p[i] = &b[i];

}

for (int i = 0; i < 5; i++) {

cout << "p[" << i << "]->a: " << p[i]->a << " b[" << i << "].a : " << b[i].a << "\n";

}

return 0;

}
?
2010-11-06 00:45:50 UTC
You initialize an array of pointers just as you would any other array, you assign values to positions. That wouldn't cause memory leaks.



What causes memory leaks is the creation of objects (either explicitly or implied) and then not cleaning up after yourself. Every "new" needs a "delete". Every "malloc" needs a "free".



Watch for implied creations like trying to use classes like primitive data types. The most notorious there is the string class. Like any other object, any string created needs to be deleted.



Hope that helps you find your leak!
Ratchetr
2010-11-06 00:46:48 UTC
It really, really, really depends on what you are trying to do here.



Can you at least post a snippet of code, with how you are trying to initialize your array?



One basic rule: For every new, you must have a delete, or you will have memory leaks. They shouldn't kill your computer, though.
oops
2010-11-06 01:03:59 UTC
Note, this code assumes you are using a modern compiler, like GCC 4.5 or VS2010.



#include

struct MyStruct

{

    int a,b,c;

};



int main()

{

    const std::size_t my_size = 25;



    std::array , my_size> my_array;

    for(auto it=my_array.begin(); it!=my_array.end(); ++it)

        *it = std::auto_ptr(new MyStruct);



    my_array[0]->a = 7;

    my_array[23]->b = 44;

    my_array[17]->c = 19;

}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...