Help with malloc and a complex struct

This is a discussion on Help with malloc and a complex struct within the C Programming forums, part of the General Programming Boards category; Dear C programmers, I am having some serious issues when trying to dynamically allocate memory for a complex (at least ...

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    31

    Help with malloc and a complex struct

    Dear C programmers,

    I am having some serious issues when trying to dynamically allocate memory for a complex (at least to me) struct I need to use in order to input experimental data into my program.

    The data consists of a number of trajectory clusters, each with a number of trajectories, each one of these defined by an x,y,z point over a number of timesteps. In addition, I assign different rgb colors for each cluster and other small details. The problem is that I do not know the number of clusters, trajectories, or timesteps until I read in the data file. Hence the need for dynamic allocation.

    The structs I came up with to handle my data are:

    Code:
    typedef struct _timestepType {                
        int id;
        float x,y,z; 
    } timestepType;
    
    typedef struct _trajectoryType {
        timestepType *timestep;                    
    } trajectoryType;
    
    typedef struct _clusterType {
        float r,g,b;                           
        trajectoryType *trajectory;       
    } clusterType;
    
    clusterType *Cluster;
    I.e., I work with objects that look like the following

    Code:
    Cluster[i].r
    Cluster[i].trajectory[j].timestep[k].x
    I confess that, even after a good dose of online tutorials, I am still very confused as to how to handle the dynamic memory allocation of something like this. A search in this forum showed me some posts with somewhat similar issues, but I am afraid I am still quite in the dark.

    Could anyone help me out with this?

    Thanks very much,

    mc61

  2. #2
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    you should allocate memory for each pointer
    starting with cluster
    Code:
    Cluster = malloc(ClusterNumber * sizeof *Cluster);
    then for each member of this array you will allocate the memory for trajectory member
    Code:
    for(i=0;i<ClusterNumber ;i++)
    {
       Cluster[i].trajectory = malloc (trajectoryNumber * sizeof *Cluster[i].trajectory );
       /* initialize here each member of Cluster[i].trajectory array */
    }
    and so on
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  3. #3
    Registered User
    Join Date
    Dec 2007
    Posts
    31
    Dear vart,

    Thank you so very much!

    mc61

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21