function returning field

ripley1321's Avatar, Join Date: Nov 2009
Newbie Member
hi, how i return field from function, which has an argument a field?

for example:

word f(word a[5]) {
word b[5];
for(int i= 0; i<5; i++) b[i] = -a[i];

return b[5]; //is this right?
}

or should i do it like this?
word *f(word a[5]) {
word b[5];
for(int i= 0; i<5; i++) b[i] = -a[i];

return *b;
}

and when i want to call function f, how can i do that? is called by another function, which takes a field as an argument. thanks.
micsom_micsom's Avatar
Go4Expert Member
Code:
 f(word* a,word** b){
 int i=0;
 for(;i<5;i++)
  { 
     *b[i]=-a[i];
  }

}
its not relible to return local variables or pointers, u never know how the stack data behaves..
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
If you want to return the whole array, you will have to create it on the heap (malloc) and remember somewhere to free it. It could be easier to pass the array in:
Code:
void test3a(int a[5], int b[5])
{
	for (int i=0; i<5; i++)
		b[i]=-a[i];
}
void test3()
{
	int a[5],b[5];
	for (int i=0; i<5; i++)
		a[i]=i*2;
	test3a(a,b);
	for (int i=0; i<5; i++)
		printf("%d ",b[i]);
	printf("\n");
}
ripley1321's Avatar, Join Date: Nov 2009
Newbie Member
thanks both of you. I got it now.