简体   繁体   中英

c initialize an array of structs of structs

I have 2 structs, path and paths. Then, define an array of paths to hold my data:

enum MAX_NEIGHBOR {MAX_NEIGHBOR = 256};
enum MAX_NUM_PATHS {MAX_NUM_PATHS = 100};

typedef struct {
    int id;
    int path[MAX_NEIGHBOR];
} path;

typedef struct {
    int id;
    path pathsIKnow[MAX_NUM_PATHS];
} paths;

paths pathsIKnow[MAX_NEIGHBOR];

I am currently initializing the array in a big loop at runtime, which takes too much time. Is there a way I can initialize this without a loop, such as during definition of the paths array?

Current loop code:

void initKnownPaths() {
    for(int j=0;j<MAX_NEIGHBOR;j++){
        paths pathsToI = pathsIKnow[j];
        pathsToI.id = 999;

        for(int i=0 ;i < MAX_NUM_PATHS;i ++){
            path pathToupdate = pathsToI.pathsIKnow[i];
            pathToupdate.id = 999;
            for(int j=0 ;j < MAX_NEIGHBOR;j++){
                int cPathValue = pathToupdate.path[j];

                cPathValue = 999;
                pathToupdate.path[j] = cPathValue;
            }

            pathsToI.pathsIKnow[i] = pathToupdate;
            pathsIKnow[j] = pathsToI;

        }
    }
}

Thanks!

If you are compiling using GCC, then instead of initKnownPaths function you can replace the structure variable pathsIKnow of type struct paths by this:

paths pathsIKnow[MAX_NEIGHBOR] =
{
  [0 ... MAX_NEIGHBOR - 1] =
  {
    999,
    {
      [0 ... MAX_NUM_PATHS - 1] =
      {
    999,
    {
[0 ... MAX_NEIGHBOR - 1] = 999}}}}};

If you are not using GCC, then you should improve your existing function based on @1201ProgramAlarm's suggestions

Note: If you use the first method, your compiled binary file size will increase, however this should reduce the run-time. ( time-space tradeoff !! )

References :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM