On Thu, 27 Sep 2007 21:16:43 +0200, jacob navia
<ja***@jacob.remcomp.frwrote:
shanfeng wrote:
such as a function: f(double v[], int a)
could this function return both a integer and array?
Thank you very much. I have confused on this for a long time~
Note that arrays as such are never passed to a function in C, instead
a pointer to the first element of the array is passed and can be used
to access the elements of the array; the effect is the same as passing
the array itself by-reference in some other languages. In this case
f() can store data into the array passed by the caller, if it is large
enough and is not defined as 'const'. That is probably the most
commonly used method in C, and thus usually the one most easily
understood by others reviewing or working on your code.
There many ways to do that:
typedef struct {
int a;
int array[21];
} RTYPE;
RTYPE f(double v[],int a);
Another solution is:
int f(double v[], int a, double **pResult);
This function returns an integer and puts the
result array in *pResult.
You can't put an array in *pResult. You can put a pointer 'to' an
array, or more precisely a pointer to the beginning of an array (of
double). But the space pointed to must be allocated somehow:
+ statically -- but not safely reusable, reentrant, or threadsafe;
+ dynamically -- but caller must take responsibility for free'ing it.
Yet another solution is:
int f(double v[], int a, int *pintResult,double **pResult);
This function returns an eror code. If the error code is
zero, pintResult will be filled with an integer and
*pResult will contain an array.
*pintResult get an int, and *pResult will _point to/at_ array.
>
And last but not least:
int *f(double v[], int a);
This function returns a pointer to a counted array. The first
element is the length, followed by an array of that length
Which again has to be allocated somehow, and only works if the desired
array element type is also int -- OP didn't say, and his only example
data was double.
- formerly david.thompson1 || achar(64) || worldnet.att.net