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?

>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;
}

Leave a Reply