Page 1 of 1

array functions

Posted: Wed Aug 28, 2002 12:04 pm
by ec3_limz
Hi.

How do I write a function that returns an array of integers in C? Preferably I do not have to use pointers.

Pls reply.

Regards,
ec3_limz

Posted: Wed Aug 28, 2002 3:27 pm
by Ivor
The only way to return an array is to return the pointer to the first element in the array. And you'll have to allocate this array within your function.

[c]int *returnInt()
{
return (int *)malloc(400 * sizeof(int));
}[/c]

This function returns int array of size 400. I guess I wrote the syntax correctly.

There's also a possiblilty to use static int array, but this array will contain it's values upto the next call to the function.

[c]int *returnInt()
{
static int a[400];

return a;
}[/c]

I guess this would also work.

About not using pointers. You can use pointer as a base -- indexing can still go through brackets.

Ivor

Posted: Fri Aug 30, 2002 3:46 am
by AlexandreN
There is another way. :)

[c]

typedef struct {
int data[ 400 ];
}Array;

Array returnArray() {

Array a;
return a;

}

[/c]

This also return a array of 400 int but you have to use a struct.

Posted: Fri Aug 30, 2002 8:20 am
by Ivor
You're right. But are you aware how much time per each call will this kind of approach consume? :roll:

Ivor

Posted: Fri Aug 30, 2002 9:42 pm
by AlexandreN
I'm sure that this is infinitely slower than the pointer approach.
I wrote it only as an alternative to pointers but I don't say that it's a better approach, only a diferent one.
I use pointers too. :)