orlowiczg
orlowiczg

Reputation: 23

Access to array (member of structure) in array of structures in C

I have problem with access to array (member of structure) in array of structures. Code sample:

struct SV
{
    int station;
    double* tab;
    SV()
    {
     double* tab= new double[3];
    }

};

int main()
{
    SV* SUV = new SV[10];

    SUV[0].station = 10; // works
    SUV[0].tab[0] = 10; //  how it should be done?

    return 0;
}

How can I get access to this array? Is it possible in C? Thanks in advance!

Upvotes: 0

Views: 104

Answers (1)

Arnav Borborah
Arnav Borborah

Reputation: 11807

In your struct SV:

struct SV
{
    int station;
    double* tab;
    SV()
    {
     double* tab= new double[3];
    }

};

In the constructor, you do:

double* tab= new double[3];

However, what you need to do is:

tab= new double[3];

The previous is not what you want since it creates a new array called tab local to the constructor, and does not initialize the one in your class. Trying to index this array will invoke undefined behavior, since tab doesn't point to anything. This also creates a memory leak, the since the local array is not deleted.

On the other hand, you could also do this in your constructor:

SV() : tab(new double[3]) {};

This would initialize tab in the constructor, not assign to it.

As a side note, I recommend that you check out std::vector to greatly simplify your task.

Upvotes: 3

Related Questions