Dynamic array of structs

I have problem with C/C++ syntax in the following code.
I need to create an array of structs. Each struct contains a float variable and a pointer to another array of the same type. Pls note that I'm allocating memory dynamically because the real array size will be known at runtime (although constants are used in this example).
Everything works fine but I'm still having problem with the part commented by question marks. The allocation goes smooth but afterwards I have problems assigning the values to the newly created array.
Will appreciate any help.
Thanks a lot.
MArcel
#include <iostream>
 
// sigle element structure
struct myElement
{
    float fValue;
    myElement *funcArgs; // pointer to array of structs
};
// pointer to the main array of elements
myElement *myArray;
 
 
// main
int main (int argc, char** argv)
{
    // allocate array
    myArray = (myElement*) malloc(sizeof (myElement) * 10);
    if (myArray == NULL)
    {
        std::cout << "Memory allocation error" << std::endl;
        return 1;
    }
 
    // fill the elements
    for (unsigned int i = 0; i < 10; i++)
    {
        (myArray + i)->fValue = i;
        // ?????
        (myArray + i)->funcArgs = (myElement*) malloc(sizeof (myElement) * 2);
        (myArray + i)->funcArgs[0] = (myArray + i);
        if (i == 0)
            (myArray + i)->funcArgs[1] = myArray + i;
        else
            (myArray + i)->funcArgs[1] = myArray + i - 1;
        // ?????
    }
 
    // release memory
    // i know, i'll have to release (myArray + i)->funcArgs[] pointers too
    free(myArray);
 
    return 0;
}

Open in new window

LVL 1
darkriserAsked:
Who is Participating?
 
evilrixConnect With a Mentor Senior Software Engineer (Avast)Commented:
It now builds. I've commented what I changed to make it do so. My changes were isolated to just making it build, I did not look at the logic of the code or its validity; however, you appear to have at least one memory leak. Also, consider using new/delete new[]/delete[]  instead of malloc/free.
#include <iostream>
 
// sigle element structure
struct myElement
{
    float fValue;
    myElement *funcArgs; // pointer to array of structs
};
// pointer to the main array of elements
myElement *myArray;
 
 
// main
int main (int argc, char** argv)
{
    // allocate array
    myArray = (myElement*) malloc(sizeof (myElement) * 10);
    if (myArray == NULL)
    {
        std::cout << "Memory allocation error" << std::endl;
        return 1;
    }
 
    // fill the elements
    for (unsigned int i = 0; i < 10; i++)
    {
        (myArray + i)->fValue = (float)i; //<--- RX: You need to cast i to a float
        // ?????
        (myArray + i)->funcArgs = (myElement*) malloc(sizeof (myElement) * 2); //<--- RX: This leaks (also, use new and delete)
        (myArray + i)->funcArgs[0] = *(myArray + i); //<--- RX: You need to dereference the rhs
        if (i == 0)
            (myArray + i)->funcArgs[1] = *(myArray + i); //<--- RX: You need to dereference the rhs
        else
            (myArray + i)->funcArgs[1] = *(myArray + i - 1); //<--- RX: You need to dereference the rhs
        // ?????
    }
 
    // release memory
    // i know, i'll have to release (myArray + i)->funcArgs[] pointers too
    free(myArray);
 
    return 0;
}

Open in new window

0
 
trigger-happyCommented:
I don't really know how to fix that yet (still finding out) but why not use the std::vector? It functions exactly like a dynamic array and will handle allocations and deallocations automatically for you.

--trigger-happy
0
 
darkriserAuthor Commented:
trigger-happy:Thanks for response.
I need a huge performance. Of course, I tested vectors, but they are too slow compared to pure arrays and pointer-addressing.
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
oleberCommented:
I have to see this as a homework and it is your work to findit out, thus not help you if I get you a solution.

Or, it isn't a homework and you sahall have some sort of dinamic array.

In +- all C/C++ compiler you can have std::vector, check information in:
http://www.cppreference.com/cppvector/index.html
0
 
evilrixSenior Software Engineer (Avast)Commented:
>> I have to see this as a homework and it is your work to findit out, thus not help you if I get you a solution.
It is ok to help someone who has posted code where (a) they are clearly making an effort and (b) the problem is that they can't figure out a compilation error that causes it not to build This is hardly the same as doing their homework for them. Syntax errors relating to pointer dereferencing can be especially tricky to resolve and even experienced programmers sometimes just need a second eye!

@darkriser, that said... there are some design issues with this code and I'd urge you to reconsider using vectors. I write high performance lexical parsers for a living. We make ubiquitous use of STL and I can assure you that using a vector properly is (almost) just as fast as using a raw array. In fact, a vector is guaranteed by the standard to just be a container class for a contiguous block of memory. The key thing is how you use it. Make sure you pre-size your vector where possible (to avoid multiple heap allocations), do not insert or delete in the middle of it (if you need to do this use a list), only push and pop from the back. Also, using a vector will save you from the main of mean management and allow you to avoid memory leaks.

If you still want to do this without a vector an I recommend you consider using a smart pointer (RAII idiom) such as boost::shared_ptr or, probably more appropriate in this case, boost::shared_array?

http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization
http://www.boost.org/libs/smart_ptr/shared_ptr.htm
http://www.boost.org/libs/smart_ptr/shared_array.htm

-Rx.
0
 
abithCommented:
>> (myArray + i)->funcArgs[1] = myArray + i;
here you are tring to reference  a mem location where value is required. as evilrix mentioned you need to derefence by changeing  *(myArray + i)
0
 
oleberCommented:
Is it showing the compiling problem?

Of course that I help if he shows the wrong code. If it is just doing the simple code, and asking you to do the real problem, you are not helping him. In the future working place he will need to know how to fix a simple problem and we will not be there to help.
0
 
evilrixSenior Software Engineer (Avast)Commented:
>> as evilrix mentioned you need to derefence by changeing  
And since I mentioned it why was it necessary to repeat it?
0
 
abithCommented:
any harm?

anyway i also mentioned why deference required here, as make my sentence coompleted i can not mentione only the statment which is required and mentioned by you. so i mentioned both.
0
 
evilrixSenior Software Engineer (Avast)Commented:
>> any harm?
My Q was why was it necessary to repeat what I had said?

Harm, yes -- it undermines the whole principle of how EE works, someone asks a Q, someone provides the correct answer and is awarded points and recognition for doing so. To repeat an answer without providing any added benefit or additional clarification might be considered an attempt point poaching. Let someone else answer the Q and then you just repeat that answer in a hope of getting a few split points! On this occasion I'll assume that wasn't the intent.
0
 
abithCommented:
what is the reply for

>> anyway i also mentioned why deference required here, as make my sentence coompleted i can not mentione only the statment which is required and mentioned by you. so i mentioned both.
0
 
darkriserAuthor Commented:
Thanks a lot. I didn't expect it to be so easy. Yes, my fault...
0
All Courses

From novice to tech pro — start learning today.