johnbakers
johnbakers

Reputation: 24771

Pointing at an array to get all its contents

So, arrays are pointers to their first element.

float color[4]={rColor, gColor, bColor, alpha};

Thus, just plain color points to &color[0];

Now suppose I have a struct thusly:

struct Colors{
float color[4];
};

Now I have found I can do this quite fine:

Colors myColor={{*color}};

I could also just do this:

Colors myColor={{color[0]}};

I am only pointing at one element, but the struct expects 4, so it keeps looking past this element.

First, I want to check that is fine to do, legal and okay. Obviously if you are passing a large array, this is quite convenient on the syntax and typing.

Second, I want to verify the reasoning about why this works. Since color alone is a pointer, the * is an indirection operator that retrieves the memory pointed to, thus, the array. So essentially we get the entire array by just calling its pointer with indirection. Correct?

Upvotes: 3

Views: 96

Answers (3)

Richard
Richard

Reputation: 61389

Using this test code:

#include "stdio.h"

int main(){
    int i;
    int color[4]={1,2,3,4};
    int ted[4]={*color};

    for(i=0;i<4;i++)
        printf("%d ",ted[i]);
    printf("\n");
}

One can easily verify that only the first element of ted is being initialized by your code. This is because *color points only to the first element of color. So the initialization list is only one item long.

Since neither C nor C++ knows the length of an array it is not possible for the compiler to automagically copy ever element of the array in the way you hope.

Upvotes: 1

mgr
mgr

Reputation: 342

if you initialize Colors like this

Colors myColor={{*color}};

you copy the first array element of the color array the rest will be initialized with zero.

Upvotes: 1

Jens Gustedt
Jens Gustedt

Reputation: 78943

Intializers of structures, unions and arrays have the particular property that elements that are omitted from it are initialized with 0.

To initialize a whole structure as your Colors you can also use any other object of that same type.

Upvotes: 1

Related Questions