Home > Blockchain >  How to create an array of initialized pointers
How to create an array of initialized pointers

Time:11-12

I have a structure:

struct Path{
    int8_t maxtopy;
};

And I want to create an array of pointers to structure Path. I've tried something like that:

int main(){
    struct Path *paths[NUMBER_OF_PATHS]; 
    init_paths(paths);
}
void init_paths(struct Path **paths){
    paths[0]->maxtopy = -1;

    for(int i = 1; i < NUMBER_OF_PATHS; i  )
        paths[i]->maxtopy = -1;
}

It is not going to work. Value to the first path is assigned correctly. But when for loop starts I am gettting Segmentation fault. I already figured out that when I am creating array of pointers, only the first pointer is going to be assigned to some structure. So I cannot e.g. paths[1]->maxtopy = -1;, because paths[1] doesn't point to any existing structure.

I have tried something like this:

for(int i = 1; i < NUMBER_OF_PATHS; i  ){
        static struct Path a;
        paths[i] = &a;
        paths[i]->maxtopy = i;
}

It doesn't work because it initialize a only once. So every pointer in paths array points to the same structure.

My question is: How to create an array of pointers that point to initialized structures?

CodePudding user response:

You've created an array of pointers, butt the pointers need to point to something. You can dynamically allocate each with malloc.

struct Path{
    int8_t maxtopy;
};

int main(void) {
    struct Path *paths[NUMBER_OF_PATHS]; 

    for (size_t i = 0; i < NUMBER_OF_PATHS; i  ) {
        paths[i] = malloc(sizeof(struct Path));
        paths[i]->maxtopy = i;
    }

    return 0;
}

Of course, if your array is declared in main and is not of excessive size, you may want to simply write the following.

int main(void) {
    struct Path paths[NUMBER_OF_PATHS]; 

    for (size_t i = 0; i < NUMBER_OF_PATHS; i  ) {
        paths[i].maxtopy = i;
    }

    return 0;
}

CodePudding user response:

const int NUMBER_OF_PATHS = 10;

struct Path {
    int8_t maxtopy;
};

void init_paths(struct Path** paths) {
    for (int i = 0; i < NUMBER_OF_PATHS; i  ) {
        paths[i] = (Path*)malloc(sizeof(Path));
        paths[i]->maxtopy = i;
    }
}

int main() {
    struct Path* paths[NUMBER_OF_PATHS];

    init_paths(paths);

    for (auto i : paths) {
        printf("%d\n", i->maxtopy);
    }
}
  •  Tags:  
  • c
  • Related