function returning field

Discussion in 'C' started by ripley1321, Nov 5, 2009.

  1. ripley1321

    ripley1321 New Member

    Joined:
    Nov 5, 2009
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    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 = -a;

    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 = -a;

    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.
     
  2. micsom_micsom

    micsom_micsom New Member

    Joined:
    Mar 23, 2009
    Messages:
    29
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Embedded C Programmer
    Location:
    India,Hybd
    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..
     
  3. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    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");
    }
    
     
  4. ripley1321

    ripley1321 New Member

    Joined:
    Nov 5, 2009
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    thanks both of you. I got it now. :)
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice