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 set a value to the components of a pointer structure

We need to allocate memory for a structure but i want to set a value to its components.

typedef struct val_s {
    int num_choice;
    int *choices;
} val_t;

the allocation with int n=4

val = malloc(n*sizeof(val_t));
if (val == NULL) {
    exit(1);
}

for (int i = 0; i < n; ++i) {
    val[i].choices = malloc(val[i].num_choice * sizeof(int));
    if (val[i].choices == NULL) {
        exit(1);
    }
}

Now if i want to set for example num_choices=2 and *choices=[0,1] How do i do that?

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

>Solution :

You can’t assign values to an array like that, so you need to do them one by one. If you have many of them, use a loop.

Example:

for (int i = 0; i < n; ++i) {
    const int num_choice = 2;

    val[i] = (val_t){num_choice, malloc(num_choice * sizeof(int))};

    // check that allocation succeeded before using the memory
    if (val[i].choices == NULL) {
        exit(1);
    }

    // assign the values:
    val[i].choices[0] = 0;
    val[i].choices[1] = 1;
}
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