Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create an array of initialized pointers

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading