0

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!

9
  • 2
    That would appear to be C++, not C. Commented Aug 4, 2017 at 15:51
  • 1
    OP, your code is C++, but your text says see. Now which one is it? Commented Aug 4, 2017 at 15:52
  • You have missing semicolons after the first 3 statements in main. If you put them at the end it compiles ok. Not making any comments about the code only that it compiles (it compiles mutatis mutandis that is not as it is). Commented Aug 4, 2017 at 15:52
  • It is C/C++, I would like to make it working without using classes. Commented Aug 4, 2017 at 16:02
  • 1
    If you are using C++, then a struct is basically a class. Commented Aug 4, 2017 at 16:02

1 Answer 1

3

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.

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

Comments

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.