Skip to content

Pointing at an array to get all its contents

An answer to this question on Stack Overflow.

Question

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?

Answer

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.