How to assign values to an array of structures in C language?

There are a few different methods for assigning values to an array of structures in the C language.

  1. Assign values one by one: use a loop to assign values to each member of the structure.
struct Student {
    int id;
    char name[50];
};

int main() {
    struct Student students[3];

    for (int i = 0; i < 3; i++) {
        students[i].id = i + 1;
        sprintf(students[i].name, "Student %d", i + 1);
    }

    return 0;
}
  1. Initialize a list using an array: when defining an array of structures, assign values to all members at once through an array initialization list.
struct Student {
    int id;
    char name[50];
};

int main() {
    struct Student students[3] = {
        {1, "Student 1"},
        {2, "Student 2"},
        {3, "Student 3"}
    };

    return 0;
}
  1. You can copy the values of one array of structures to another array of structures by using the memcpy function.
#include <string.h>

struct Student {
    int id;
    char name[50];
};

int main() {
    struct Student students1[3] = {
        {1, "Student 1"},
        {2, "Student 2"},
        {3, "Student 3"}
    };

    struct Student students2[3];

    memcpy(students2, students1, sizeof(students1));

    return 0;
}

The above are several common methods, choose the appropriate method of assignment according to actual needs.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds