How to pass a pointer to an unknown-size array?

G

Guest

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
 
V

Victor Bazarov

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);

What book are you reading that doesn't explain passing arrays to
functions?

int func(double array[], int size)
{
int index;
/* calculate index somehow */
if (index > 0 && index < size)
array[size]; /* do something with the double */
return 42;
}

V
 
E

E. Robert Tisdale

cat func.c
#include <stdlib.h>
#include <stdio.h>

int func(size_t size, const double array[]) {
size_t index;
// Calculate index somehow.
if ((0 <= index) && (index < size)) {
// Do something with the double.
fprintf(stdout, "array[%u] = %f\n", index, array[index]);
}
return 42;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top