
returning pointer from function
Quote:
>i guess you found a partial solution yourself by using an int pointer instead.
>just typedef an int pointer, then allocate the space you want for that pointer
>and simply use it as the return value for the function.
>something like:
>typedeft int* vector;
typedef
Quote:
>int SIZE = 10; /* for example */
>vector YOUR_FUNCTION( ... ) {
> vector V = (int *) malloc(SIZE*sizeof(int));
Lose the cast. Even if you incluse it writing it as (int *) makes no sense
when you have explicitly created a vector typedef to avoid such details.
A better approach is:
vector V = malloc(SIZE * sizeof *V);
Quote:
> .....
> return V;
>}
>or ...
>typedef int[10] vector;
This isn't valid C syntax. To type vector as an array of 10 ints use
typedef int vector[10];
Quote:
>int *something;
>vector YOUR_FUNCTION( ... ) {
> vector V;
> .......
> return V;
>}
>something = V;
>Don't quote me on that but I think you can return an array from a function but
>you need to make sure that this array is assigned to a pointer and NOT to an
>array.
No, you cannot return an array in C (specifically you are not allowed to
declare or define a function with an array return type).
Quote:
>The pointer (something in our case) will point to the firstr character
>of the vector (the return vector).
The V in YOUR_FUNCTION is an automatic variable i.e. will cease to
exist once the function returns. So even if you do manage to return a
pointer to part of it that will cease to be valid in the caller since
it no longer points to a valid object.
Quote:
>> I have a variable which I have typedef'd as follows:
>> typedef int vector[10];
It is generally best to avoid typedef'ing arrays since it produces code
that is awkward ad hard to read. Arrays behave differently to other
typess of object in C and it is important to show explicitly when
something is an array.
Quote:
>> Now, I want to write a function which returns a vector. But a function
>> can't return an array, so it has to return a pointer to int instead. Fine.
>> But, I want to maintain the abstraction by having the function return
>> something which "looks like" a vector. Something, conceptually, like:
If this is really going to be an abtract type then you could wrap the
array up within a struct.
typedef struct {
int data[10];
Quote:
} vector;
C supports passing and returning structs to and from functions although
copying large structures can be expensive. Of course you can use pointers
to the struct where appropriate. Bear in mind that the normal way of
allowing a function to change a large object like an array or structure
it to pass a pointer to an object created in the caller to the function as
an argument and then the function can write to the object directly.
--
-----------------------------------------
-----------------------------------------