Hey Guys. Been awhile since I've been on, so I wanted to drop in and let ya know that I haven't given up on WZ2100. I got my programming books a few weeks ago, and I've been having a right fun time with them (multi-dimensional arrays are fun). I'm currently working through defining functions, which is something I vaguely knew how to do going in, but there's a lot of stuff a apparently missed out on by reading web docs on C.
Which I suppose leads me to bring up a little trouble I've been having. Is there anyway to return more than one variable? And is there any way to return an array? I know they're just stupid questions, and I'll probably find out for myself if I keep reading, but there is a little side project I've been working on to hone my skills, and it's stuck until I can get those out of the way. Thanks all, and see ya later.
Just Dropping In
-
DevUrandom
- Regular

- Posts: 1690
- Joined: 31 Jul 2006, 23:14
Re: Just Dropping In
All code is C99.
If you want to return error codes in "addition", it depends on the conventions of your API.
For example you return UINT_MAX or NULL to indicate an error.
Code: Select all
typedef struct { int a, b; } myStruct_t;
// Of course you don't declare structs just for the fun itself
// (i.e. not just to return multiple values, without using the type in some other place)
myStruct_t myMultiReturnFunction(void)
{
 return (myStruct_t){ 2, 3 }; // Return a struct containing two integer values: 2 and 3
}
// Better in case the type you want to return is not a struct like the above:
void myMultiReturnFunction2(int *a, int *b)
{
 *a = 2; // Set memory at the provided pointers
 *b = 3;
}
For example you return UINT_MAX or NULL to indicate an error.
Code: Select all
// Bad practise, as long as it is not exactly clear who is to free(array);
char * myArrayReturnFunction(void)
{
 char * array = malloc(10); // Allocate a piece of memory, size: 10 bytes
 for (unsigned int i = 0; i < 10; i++)
array[i] = i; // Initialise with 0,1,2,...
 return array; // Return pointer to memory
}
// A little bit better:
typedef struct { char a[10] } myArrayWrap_t;
myArrayWrap_t myArrayReturnFunction2(void)
{
 return (myArrayWrap_t){ {0,1,2,3,4,5,6,7,8,9} }; // Return a struct containing an array
}
// Probably prefered:
void myArrayReturnFunction3(char array[], unsigned int size)
{
 for (unsigned int i = 0; i < size; i++)
array[i] = i; // Set memory at provided pointer, take care of the size
}
[/quote]