Thread: assigning values to a dynamically allocated array of structures

  1. #1
    Registered User
    Join Date
    Nov 2008
    Posts
    2

    assigning values to a dynamically allocated array of structures

    Hi,
    I am trying to dynamically create an array of structures of type page. The page struct looks like this:

    Code:
     typedef struct
    {
       unsigned short int proc_no;
       unsigned short int page_no;
    } page;
    Then in a function called set_trace, I am using malloc to dynamically create the array. I believe thus far my code is correct, but the next thing I'm trying to do is enter values into this array of structs. This is what my set_trace function looks like.

    Code:
     void set_trace( unsigned short int proc_no, unsigned short int trace[], page *pPter  )
    {
       pPter = malloc( sizeof( page ) * trace_size );
       for( int n = 0; n <= trace_size; n++ )
       {
          pPter.process_number = proc_no;
          pPter.page_number = trace[n];
       }
    }
    For each iteration of the loop, I am trying to assign the proc_no and the value at trace[n] to the nth page in the array. Can someone show me how to do this?

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    You need to pick a structure first out of your array to assign in to, and then assign it:
    Code:
    pPter[n].process_number = proc_no;
    pPter[n].page_number = trace[n];
    Note that you are trashing memory because your for-loop takes one too many steps.

  3. #3
    Registered User
    Join Date
    Nov 2008
    Posts
    2
    thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. can't assign proper values to an array of string
    By Duo in forum C Programming
    Replies: 1
    Last Post: 04-04-2005, 06:30 AM
  2. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  3. 2 Dimenstional Array vs Array of Structures
    By jrahhali in forum C++ Programming
    Replies: 2
    Last Post: 04-11-2004, 04:51 AM
  4. Merge sort please
    By vasanth in forum C Programming
    Replies: 2
    Last Post: 11-09-2003, 12:09 PM
  5. Hi, could someone help me with arrays?
    By goodn in forum C Programming
    Replies: 20
    Last Post: 10-18-2001, 09:48 AM