Thread: its me again

  1. #1
    Registered User
    Join Date
    Feb 2002
    Posts
    11

    Unhappy its me again

    hi

    thanx to all people who replied my previous q..


    lol ive another question

    how i can return a pointer to an array of structures?

    thanx

    for example in this function

    struct* StoreData(int job, int arrival, int service, int leaving)
    {
    struct data
    {
    int j;
    int a;
    int s;
    int l;
    };

    struct data mydata [20];


    mydata[job-1].j=job;
    mydata[job-1].a=arrival;
    mydata[job-1].s=service;
    mydata[job-1].l=leaving;
    return mydata;
    i donno i always got an error considering the returned value
    thanx alot again

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    You can't return pointers to local data. Local variables go out of scope when the function exits, so your pointer is no longer valid.

    Ways out are
    1. Pass the array as a parameter to the function
    2. Make the local array static
    3. Allocate a dynamic array and return that

  3. #3
    Registered User
    Join Date
    Feb 2002
    Posts
    11

    about My Last post

    Thanx for those who replied..whether they were sarcastic
    or not..im just a beginner of C++..i am not a shame to ask anything..even if it was a stupid question..i guess

    about this code ive written ..i can read it as i could write it;however, it gives me a compiling error this is why i asked what's wrong wiz it ..so simple!!

  4. #4
    Registered User
    Join Date
    Feb 2002
    Posts
    11

    Talking the Error

    --------------------Configuration: trial1 - Win32 Debug--------------------
    Compiling...
    trial1.cpp
    E:\ass#210\ass6tr1\trial1.cpp(389) : error C2440: 'return' : cannot convert from 'struct Data *' to 'struct $S9 *'
    Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
    Error executing cl.exe.

    trial1.exe - 1 error(s), 0 warning(s)

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Your struct should be outside the function, not inside
    Code:
    struct data 
    { 
    int j; 
    int a; 
    int s; 
    int l; 
    }; 
    
    data *StoreData(int job, int arrival, int service, int leaving) 
    { 
       data mydata [20]; 
    
    }

Popular pages Recent additions subscribe to a feed