ionick
ionick

Reputation: 146

C++ referencing an array of structs

I'm new to using C++ for complicated programming. I've been sifting through some leftover, uncommented, academic code handed down through my department, and I've stumbled across something I have no real idea how to google for. I don't understand the syntax in referencing an array of structs.

Here is a trimmed version of what I'm struggling with:

typedef struct
{
    double x0,y0;
    double r;
} circle;

double foo()
{
    int N = 3;
    double mtt;
    circle circles[N];

    for (int i = 0; i < N; i++)
    {
        mtt += mtt_call_func((circles+i), N);
    }

    return mtt;
}

What does (circles+i) mean in this case?

EDIT: the function should have (circles + i), not (circle + i).

Upvotes: 1

Views: 80

Answers (4)

Dragos Rizescu
Dragos Rizescu

Reputation: 3488

Each vector you declare in stack it's actually a pointer to the first index, 0, of the vector. Using i you move from index to index. As result, (circles+i) it's the equivalent of &circles[i].

& means the address of the variable. As in your function call, you send a pointer which stores an address of a variable, therefore & is required in front of circles[i] if you were to change to that, as you need the address of the i index of the vector circles to run your function.

For more about pointers, vectors and structures check this out: http://pw1.netcom.com/~tjensen/ptr/pointers.htm

It should cover you through ground basics.

Upvotes: 0

4pie0
4pie0

Reputation: 29724

circle+i means "take a pointer circle and move it i times by the size of the object pointed to by it". Pointer is involved because the name of the array is a pointer to it's first element.

Apart from this you should initialize an integer counter variable that is used in loop:

for (int i = 0; i < N; i++)
           ^^^^
{
    mtt += mtt_call_func( ( circles + i), N);
                                  ^ // typo
}

Upvotes: 2

M.M
M.M

Reputation: 141574

circles+i is equivalent to &circles[i]. That's how pointer arithmetic works in C++.

Why is there a pointer? Well, when you give the name of an array, in a context other than &circles or sizeof circles, a temporary pointer is created that points to the first member of the array; that's what your code works with. Arrays are second-class citizens in C++; they don't behave like objects.

(I'm assuming your circle+i was a typo for circles+i as the others suggested)

Upvotes: 3

Jeremy Roman
Jeremy Roman

Reputation: 16355

In C, as in C++, it is legal to treat an array as a pointer. So circles+i adds i times the size of circle to the address of circles.

It might be clearer to write &circles[i]; in this form, it is more obvious that the expression produces a pointer to the ith struct in the array.

Upvotes: 1

Related Questions