array functions

Write here if you have problems with your C source code

Moderator: Board moderators

Post Reply
ec3_limz
Learning poster
Posts: 79
Joined: Thu May 23, 2002 3:30 pm
Location: Singapore

array functions

Post 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
Ivor
Experienced poster
Posts: 150
Joined: Wed Dec 26, 2001 2:00 am
Location: Tallinn, Estonia

Post 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
There is a theory which states that if ever anyone discovers exactly what the Universe is for and why it is here, it will instantly disappear and be replaced by something even more bizarre and inexplicable.
AlexandreN
New poster
Posts: 27
Joined: Sun Jul 07, 2002 6:46 pm
Location: Campina Grande - Brazil
Contact:

Post 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.
Ivor
Experienced poster
Posts: 150
Joined: Wed Dec 26, 2001 2:00 am
Location: Tallinn, Estonia

Post by Ivor »

You're right. But are you aware how much time per each call will this kind of approach consume? :roll:

Ivor
There is a theory which states that if ever anyone discovers exactly what the Universe is for and why it is here, it will instantly disappear and be replaced by something even more bizarre and inexplicable.
AlexandreN
New poster
Posts: 27
Joined: Sun Jul 07, 2002 6:46 pm
Location: Campina Grande - Brazil
Contact:

Post 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. :)
Post Reply

Return to “C”