Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Function that return a usable array of pointers to structures.

Status
Not open for further replies.

UncleRic

Programmer
Apr 27, 2007
1
0
0
US
I'm trying to figure out how to create a usable array of pointers to structures.

Essentially, I want to call a function that return a usable array of pointers to structures.

From what I've learned so far, you allocate the structure array by doing a malloc of the structure, multiplied by the number of elements of the array as indicated in the following code:

C:
typedef struct {
        char* name;   /* '\0'-terminated C string */
        int   number;
    } myStructure;

void *myFunction(int n);

int main() {
   int n = 5;
   myStructure *myData[n] = myFunction(n);    // ...correct?
   // ....
   free(myData);
} // main()

// ------------------------------------------------------------------------------------

void *myFunction(int n) {

    // I want to reserves space for n 'myStructures' via the following syntax.
    // Shouldn't use [] in declaration; hence the 'n' counter in the sizeof().

    myStructure *ricData = (myStructure *)malloc(sizeof(myStructure)*n);
    
    // This works:
    ricData->number = 123;
    ricData->name = "Ric Lee\0";
    
    // This  also works:
    printf("\nricData[0].name= %s",ricData[0].name);
    
    // Load value into [1]:
    ricData[1].number = 345;
    ricData[1].name = "Richard D. Brauer\0";

    // This also works:
    printf("\nricData[1].name= %s\n",ricData[1].name);
    
    // What happens when I load BEYOND 5 elements?
    ricData[7].number = 777;
    ricData[7].name = "Mydle Oogalbee";
    
    printf("\nricData[7].name= %s",ricData[7].name);  // Debugger sees it. 

    return &ricData;     // Is this correct: addr to array of pointers to structures?

} // end myFunction().

I'm not sure if this is the correct syntax. I purposely loaded values beyond the array size to see what would happen. The debugger showed the mapping to be successful. But enabling the 'Malloc Guard' option to the debugger flagged this error.

1) Am I correctly creating & loading structures of an array of ptrs, into dynamic memory?

2) Do I return the address (&struct) of the array of structure pointers to the calling program?

Regards,

Ric.
 
Code:
myStructure *myFunction(int n);

int main() {
   ...
   myStructure *myData = myFunction(n);    // ...correct?
   ....
} // main()

myStructure *myFunction(int n) {

   ...

   return ricData;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top