Thread: Help with malloc and a complex struct

  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
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    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
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  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