views:

79

answers:

3

hi.

Suppose I have some pointer, which I want to reinterpret as static dimension array reference:

double *p;
double (&r)[4] = ?(p); // some construct?

// clarify
template< size_t N> void function(double (&a)[N]);
...
 double *p;
function(p); // this will not work.
//  I would like to cast p as to make it appear as  double[N]

Is it possible to do so? how do I do it?

A: 

Yes, it's called a vector :)

std::vector<double> myVariableArray(4)

EDIT: Rereading, it looks like you want to get the size an array was declared with. You can't do that -- that's a template method feature you can use on occasion. Since a double * doesn't even need to point to doubles there's little way a compiler could give you a sensible answer in any case.

Billy ONeal
Eh, not the same.
GMan
@GMan: Yeah -- just realized that. Edited. Initially interpreted that as "Can I create an array with a dimension known at runtime"
Billy ONeal
+3  A: 

It's ugly:

double arr[4];
double* d = arr;

double (&a)[4] = *static_cast<double(*)[4]>(static_cast<void*>(d));

Be sure the array type matches what the pointer originally came from.

GMan
`double(*)[4]`, what is this construct? this is the first time I see it
aaa
@aaa: That's a pointer to an array of 4 doubles.
GMan
one last question, why cast to void* first?
aaa
@aaa: We could do: `reinterpret_cast<double(*)[4]>(d)`, but this relies on implementation defined behavior. C++ standard guarantees that a cast from `void*` to `T*` will always work as long as the `void*` originally pointed at that `T`. The code above is well-formed, because `d`, when casted to `void*`, does indeed point to the original type we are casting to. (This is also why I warn the cast matches exactly what the pointer points at. If we were to cast to anything else, we'd have undefined behavior.)
GMan
what if d was `new double[]` originally, rather than pointer to double[4]? would `a` still be valid (in first four elements)? I was not quite clear if by type T you meant double or `double[4]`.thank you
aaa
By `T` I meant `double[4]`. I *think* that should work because `double` is a POD type. Hopefully someone else can chime in to confirm.
GMan
A: 
double *array;
...
...
int sizearray = sizeof(array)/sizeof(double);
Luiguis
The logic here is wrong. `array` carries no information about what it points to. This will always return the same answer, no matter what.
GMan
sizeof(array) when array is a pointer will give back the pointer size, usually 4 or more depending on OS.
Anders K.