returning a struct pointer

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nano2
    New Member
    • Jan 2007
    • 41

    returning a struct pointer

    Hi,

    Have the following scenario in C. returning a copy of the structure which is not good should be passing back a structure pointer

    How would i acahieve this .
    any ideas..




    int main(){

    ret = fn(b);

    }

    retSt fn( char *p)
    {
    st result ;

    fnb(&result);

    return st;

    }
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    It's very easy. Suppose your struct is named myStruct. Suppose further that your structure returning function is called structFunc(). Then your code would look like this:

    Code:
    struct myStruct {
        int sampleValue;
        string sampleName;
        double sampleValue2
    };
    
    myStruct* structFunc() { // Return type is a pointer to your struct
        myStruct *structPtr;
        structPtr = new myStruct;
    
        structPtr->sampleValue = 10;
        structPtr->sampleValue2 = 99.2;
        structPtr->sampleName = "My Struct";
    
        return structPtr; // Returns the pointer
    }

    Comment

    • r035198x
      MVP
      • Sep 2006
      • 13225

      #3
      Originally posted by nano2
      Hi,

      Have the following scenario in C. returning a copy of the structure which is not good should be passing back a structure pointer

      How would i acahieve this .
      any ideas..




      int main(){

      ret = fn(b);

      }

      retSt fn( char *p)
      {
      st result ;

      fnb(&result);

      return st;

      }
      You should practice this thoroughly (revisit the tutorials if neccessary) It is going to be relevant to all the code you are going to write.

      Comment

      Working...