GIDForums  

Go Back   GIDForums > Computer Programming Forums > C Programming Language
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 03-Sep-2007, 01:59
UncleRic UncleRic is offline
New Member
 
Join Date: Sep 2007
Posts: 1
UncleRic is on a distinguished road

How Do I Create a Function that returns a usable array of pointers to structures?


Environment: Mac OS X (10.4.10); gcc 4+.
Language: ANSI C (not C++).

Essentially, I want to call a function that returns a usable array of pointers to structures in a heap.

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:

CPP / C++ / C Code:
typedef struct {
        char* name;  
        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 in XCode 2.4.1 for 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.
  #2  
Old 03-Sep-2007, 08:01
davis
 
Posts: n/a

Re: How Do I Create a Function that returns a usable array of pointers to structures?


Quote:
Originally Posted by UncleRic
Environment: Mac OS X (10.4.10); gcc 4+.
Language: ANSI C (not C++).

Essentially, I want to call a function that returns a usable array of pointers to structures in a heap.

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:

CPP / C++ / C Code:
typedef struct {
        char* name;  
        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 in XCode 2.4.1 for 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.


You're asking a lot of questions, some contained in the text message others contained in the code, which makes it more difficult to answer you.

The fact that you have hardcoded an index of 7 in an array of hardcoded 5 elements, means that you're simply doing things in a "bad" way rather than doing them in a "good" way. You should prevent code that can ever exceed the bounds of your array rather than purposely try to insert a known bad value. If you want to try to insert a known bad value, then try passing a "bad n" to your function and see how it deals with it, not by hardcoding a bad value of "n" inside the function.

You declare "myFunction" (what a worthless name, BTW) as returning a void*. Then you return the address of the known type "myStructure*" (another worthless name) back. Is that what you want, the address of the pointer that you just allocated?

The standard library function calloc is particularly designed for allocating arrays, yet you use malloc. Fine, but why not use calloc?

Your underlined goal of calling a function to return a usable array of pointers to structures on the heap, is not exactly what you're doing. You're creating an array of structures using myFunction, but you're returning a single pointer not an array of pointers to structures.

If you meant what you said by the underlined statement, then you will want different code than what I've seen so far.

Of course, I have no idea what you're really wanting to accomplish, since you've only said "what" you're trying to do, not why you're trying to do it. Without knowing more about your purpose, it is a bit more difficult to figure out if you're doing the correct "what." How do you intend to use the array of pointers to structures.

Shouldn't we think that if what you want is an array of pointers to your structure that we should see something like:

CPP / C++ / C Code:
struct myStructure** members;

...or:

CPP / C++ / C Code:
struct myStructure* members[n];

Isn't:

CPP / C++ / C Code:
struct myStructure* members;

...as single pointer to some number of structures? Didn't you say that you want an array of pointers to your structure?


:davis:
  #3  
Old 03-Sep-2007, 11:17
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,700
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: How Do I Create a Function that returns a usable array of pointers to structures


Quote:
Originally Posted by UncleRic
Essentially, I want to call a function that returns a usable array of pointers to structures in a heap.

I'll show a main program that dynamically allocates an array of pointers to doubles and allocates an array of doubles for each pointer.


An array of pointers to "something" can be used with index notation that looks like a 2-Dimension array of "something"s, so I end up with something that can be used as a dynamically allocated 2-Dimensional array of doubles.

Putting it into a function simply requires declaring the function return type to be pointer-to-pointer-to double, and having the function return the value from the first malloc().


You can do the same kind of thing for your structs. See footnote.

CPP / C++ / C Code:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int num_arrays;
    int num_doubles;
    double **element;
    int i, j;
    double x;

    printf("Enter the number of arrays: ");
    if ((scanf("%d", &num_arrays) != 1) || (num_arrays <= 0)) {
        printf("You must enter a positive integer.\n");
        return 0;
    }
    printf("You entered %d\n\n", num_arrays);

    printf("Enter the number of doubles in each array: ");
    if ((scanf("%d", &num_doubles) != 1) || (num_doubles <= 0)) {
        printf("You must enter a positive integer.\n");
        return 0;
    }
    printf("You entered %d\n\n", num_doubles);

    element = malloc(num_arrays * sizeof(element[0])); /* one pointer for each array*/
    if (element == NULL) {
        printf("Couldn't allocate %d bytes for %d pointers\n",
                num_arrays * sizeof(element[0]), num_arrays);
        return 0;
    }

    for (i = 0; i < num_arrays; i++) {
        element[i] = malloc(num_doubles * sizeof(element[0][0]));
        if (element[i] == NULL) {
            printf("Couldn't allocate %d bytes for element[%d]\n",
                    num_doubles * sizeof(element[0][0]), i);
            return 0;
        }
    }
    x = 0.0;
    for (i = 0; i < num_arrays; i++) {
        for (j = 0; j < num_doubles; j++) {
            element[i][j] = ++x;
        }
    }

    for (i = 0; i < num_arrays; i++) {
        for (j = 0; j < num_doubles; j++) {
            printf("element[%d][%d] = %.1f  \n", i, j, element[i][j]);
        }
        printf("\n");
    }

    for (i = 0; i < num_arrays; i++) {
        free(element[i]);
    }
    free(element);

    return 0;
}

Output:
Code:
Enter the number of arrays: 2 You entered 2 Enter the number of doubles in each array: 3 You entered 3 element[0][0] = 1.0 element[0][1] = 2.0 element[0][2] = 3.0 element[1][0] = 4.0 element[1][1] = 5.0 element[1][2] = 6.0

Regards,

Dave

As my dear old dad used to say: It's exactly the same except it's different.

Also, please note that you can't make a function that returns an "array of pointers to anything", since functions can not return arrays. Functions return pointers. A "pointer-to-pointer" to structs can lead to something that is notationally equivalent to an array of pointers to structs, and that's what you can do with code similar to what I showed.
Last edited by davekw7x : 03-Sep-2007 at 12:41.
 
 

Recent GIDBlogObservations of Iraq by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
return string from a function Howard_L C Programming Language 4 17-Aug-2007 23:56
Sort an array of structures sassy99 C Programming Language 10 15-Feb-2007 07:46
[Include] Doubly-linked List dsmith C Programming Language 6 14-Apr-2006 13:12
[Tutorial] Function Pointers aaroncohn C++ Forum 4 17-Feb-2006 11:33
Pointer Usage in C++: Beginner to Advanced varunhome C++ Forum 0 19-Aug-2005 09:25

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 13:50.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.