Jump to content

How to make an array of pointers to structs in c?


SubhanUllah

Recommended Posts

... 
... 
 
//define you structure type 
typedef struct { 
                ...... 
} MyStruct; 
 
//now, the array of pointes 
 
#define MAX_MYSTRUCTS 200 
MyStruct *pointers[MAX_MYSTRUCTS]; 
 
// As you dont have space to hold your structures, you might use malloc to allocate 
// each new created structure.  So you will also need a counter to know how many 
// structures you have created. 
 
int nMyStruct = 0; 
 
// You can make a function to add a new struct 
 
int addMyStruct() { 
        void tempPointer; 
 
        // check if there is space in the array for new pointer 
        if(nMyStruct>=MAX_MYSTRUCT) return -1; 
 
        //Ask malloc for space for 1 structure 
        tempPointer = malloc(sizeof(MyStruct)); 
 
        //if pointer is null, malloc couldnt do it 
        if(tempPointer==NUL) returen -1; 
 
        //Else store the pointer and recast it 
        pointers[nMyStruct] = (MyStruct *)tempPointer ; 
         
    //return the place it was stored and add 1 to nMyStruct 
        return nMyStruct++; 
} 

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...