Thread: Returning a struct from a function call

  1. #1
    Registered User
    Join Date
    Jun 2012
    Location
    Göteborg
    Posts
    28

    Returning a struct from a function call

    Hi,

    I have a problem with returning a struct that I don't understand.
    This is just a part of my code. I get an "Incompatible types ..." error when I compile the code. I have been playing around with this code now for a while trying different things, setting '*' and '&' just everywhere. Now I'm stuck. So Please, what am I doing wrong?

    Code:
    #include <stdio.h>
    typedef struct {
      int x;
      int y;
    } Coordinate;
    
    Coordinate c;
    
    Coordinate CallF(Coordinate *c) {
      return c;
    }
    
    int main() {
      Coordinate *c_ptr;
      c_ptr = &c;
      c_ptr->x = 8;
      c_ptr->y = 5;
    
      c = CallF(&c);
      return 0;
    }

  2. #2
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,059
    Return the struct Coordinate from CallF(), not a pointer to it!

  3. #3
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    In CallF you should return the struct instead of the pointer. That means dereference using '*':
    Code:
    Coordinate CallF(Coordinate *c) {
        /* do stuff */
        return *c;
        }

  4. #4
    Registered User
    Join Date
    Jun 2012
    Location
    Göteborg
    Posts
    28
    Sorry, I don't understand how you mean. Should I use 'struct Coordinate CallF ...'?

  5. #5
    Registered User
    Join Date
    Jun 2012
    Location
    Göteborg
    Posts
    28
    OK ... 'return *c' did it. I have been trying to much so I got it completely wrong.

    Thank you for your help.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Returning struct in function
    By xeon321 in forum C Programming
    Replies: 3
    Last Post: 06-24-2012, 01:50 AM
  2. Replies: 5
    Last Post: 09-06-2011, 02:59 PM
  3. struct in function call
    By Jasper in forum C Programming
    Replies: 2
    Last Post: 09-09-2009, 02:18 AM
  4. problem returning struct member from function
    By yukster in forum C Programming
    Replies: 6
    Last Post: 08-24-2003, 01:21 PM
  5. Replies: 2
    Last Post: 05-04-2003, 05:30 AM