Re: How to pass a pointer to an unknown-size array?
- From: john_bode@xxxxxxxxxxx
- Date: 26 May 2005 07:21:51 -0700
nospam@xxxxxxxxxx wrote:
> Hello!
>
> I can pass a "pointer to a double" to a function that accepts
> double*, like this:
>
> int func(double* var) {
> *var=1.0;
> ...
> }
>
> double var;
>
> n=func(&var);
>
> ---
>
> Now I want to pass a pointer to an array of doubles, the size
> of the array must not be fixed though:
>
> int func(double[]* array) {
> int index;
> index=3;
> array[index]=1.0;
> ...
> }
>
> double array[100];
>
> n=func(&array);
>
> with the above code the compiler gives me an error. The only
> solution that I found so far is this very inelegant one:
>
> int func(void* array) {
> int index;
> index=3;
> *((double*)(array)+index)=1.0;
> ...
> }
>
> double array[100];
>
> n=func(&array);
>
> ---
>
> There must be a cleaner way.. but what is it?
>
> I am interested in both C and "C++ only" solutions.
>
> Thanks!
> Mike
int func(double *array, size_t arrsize)
{
int index = 3;
if (index < arrsize)
{
array[index]=1.0;
}
...
}
....
double array[100];
int n = func(array, sizeof array);
....
Remember that in C, the subscripting operation a[i] is *defined* as
*(a+i). Therefore, in *most* expression contexts (sizeof() being one
of two exceptions IINM), the type of a is converted from array of T to
pointer to T, and its value is set to the address of the first element
in the array (&a[0]), so the expression *(a+i) yields the correct
result. Because of this conversion, when you pass an array as a
parameter to a function, what you wind up passing is a pointer to the
base type, and its value is the address of the first element (this is
why I didn't use the address operator & in the function call above).
If you need to know the size of the array in the function, you need to
specify the array size as a separate parameter; a pointer doesn't know
the size of the chunk of memory it's pointing to.
If you wished to pass a pointer to the array object (not just a pointer
to the first element), the code would look like this:
int func(double (*array)[100]) // size must match original
{
int index=3;
(*array)[index] = 1.0;
...
}
....
double array[100];
n = func(&array);
This time, we are passing a pointer to a 100-element array of double.
Since 100-element array of double is a distinct type, this approach
won't work for arrays of different sizes.
.
- Follow-Ups:
- Re: How to pass a pointer to an unknown-size array?
- From: john_bode
- Re: How to pass a pointer to an unknown-size array?
- References:
- How to pass a pointer to an unknown-size array?
- From: nospam
- How to pass a pointer to an unknown-size array?
- Prev by Date: Re: sscanf and int64 in Win32 and Unix - different results?
- Next by Date: Re: (void) printf vs printf
- Previous by thread: Re: How to pass a pointer to an unknown-size array?
- Next by thread: Re: How to pass a pointer to an unknown-size array?
- Index(es):
Relevant Pages
|