Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   function returning field (http://www.go4expert.com/forums/function-returning-field-t20000/)

ripley1321 6Nov2009 05:11

function returning field
 
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 6Nov2009 09:59

Re: function returning field
 
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 7Nov2009 00:11

Re: function returning field
 
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 7Nov2009 02:57

Re: function returning field
 
thanks both of you. I got it now. :)


All times are GMT +5.5. The time now is 23:25.