Typedef an unconstrained float array in C
The problem you're encountering here is the fact that arrays are not pointers in C, but rather decay to pointers to the first element when used on the right-hand side of the assignment operator. Thus, if you declare an array like
fooType myArray = {1.0, 2.0, 3.0}
the type of myArray
is float[3]
, and &myArray is (*float)[3]
, or "pointer to an array of 3 floats". Thus you can't simply say
fooType *bar = myArray;
The type fooType*
is not a pointer to a float ... thus it's an incompatible pointer type. Doing
fooType* bar = &myArray;
does work, but the problem you're encountering is that bar[1]
is not an element in the array myArray
, since bar
itself is a pointer. You would have to dereference bar
like (*bar)[1]
to access an element in myArray
. For instance:
typedef float fooType[];fooType myArray = {1.0, 2.0, 3.0}fooType* bar = &myArray;(*bar)[1] = 5.0;
Finally, keep in mind that with C, you cannot assign one array to another array ... so you can'd do something like:
fooType bar = myArray;
This goes back to the whole issue of arrays and their decay into pointers to the first element, and the fact that the type of the array itself is not the same as the type of the first element in the array.
You may in the end simply want to typedef the array, and then typedef the array element types since of using float
so that anyone using your code will know what one type of element belongs with the other.
Using Visual Studio 2013 I found that you could use constructs such as in this example. This also seems to work with Visual Studio 2015.
Notice that the use of malloc()
to create an array of fooType
requires a dereferenced pointer of type pfooType
rather than the type of fooType
or *pfooType
to compile. I changed the typedef
from float
to double
and the sizeof(*p2)
changed from 4 to 8 bytes as expected.
#include <malloc.h>typedef float fooType[], *pfooType;int xxmain2(void){ fooType myArray = { 1.0, 2.0, 3.0 }; // define the array with its elements pfooType p = myArray; // get a pointer to the array. int i; int nElements = sizeof(myArray) / sizeof(*p); // determine number of elements in the array. pfooType p2 = malloc(sizeof(*p2) * 5); // malloc() an array of 5 elements. for (i = 0; i < 5; i++) p2[i] = (float)i * 10.0; // initialize my malloced array. myArray[0] = *p; // dereference pointer myArray[1] = p[1]; // use array subscripting with pointer for (i = 0, p = myArray; i < nElements; i++) *p++ = 0; // increment the pointer to traverse the array. free(p2); return 0;}
I also found that I could not create a specified size of an array with something like fooType myRay2[10];
(compilation error of "error C2087: 'myRay2' : missing subscript") or something similar. And fooType myRay2;
gives a compilation error of "error C2133: 'myRay2': unknown size".
So the only way seems to be to use initialization to size the array or to use malloc()
to create an array of a particular size which then requires free()
.