简体   繁体   中英

How to copy this struct with multiple arrays to another temporary struct?

I need to write a function void findBoursiers(void) that need to do the following tasks:

  1. copy the content of struct student m_stuTab[STU_NB] which contain 6 students with each

    a) the name of the student ( name[MAX_NAME] )

    b) the file number ( fileNumber[NB_DIGITS] )

    c) the score.

I need to copy all this to a temporary struct named struct student temp_stuTab[STU_NB] (which is created in void findBoursiers(void) ).

  1. I need take the content of struct student temp_stuTab[STU_NB] and take the 3 students with the highest score in order from best to worst. I imagine by comparing them with a for loop.

  2. Take those 3 students and put them in an array named char m_boursiers[3][MAX_NAME] .

I am required to not change this following code, which is in main()

struct student {
    char name[MAX_NAME];
    char fileNumber[NB_DIGITS];
    int score;
};

struct student m_stuTab[NB_STU];
char m_stuName[NB_STU][MAX_NAME] = {"Mario", "Yoshi", "Luigi", "Peach", "Wario", "Waluigi"};
char m_boursiers[3][MAX_NAME];

I know this is feasible with for loops, strcpy and such but I wonder if there is a more efficient way to do it. Maybe a process similar to memcpy ? I am fairly new to coding so sorry if my question is hard to understand. Thanks a lot!

 student temp_stuTab = student m_stuTab

Now I understand the actual question. C and C++ differ here, but that was wrong in any case.

C:

 struct student temp_stuTab;
 temp_stuTab = m_stuTab;

C++:

 student temp_stuTab;
 temp_stuTab = m_stuTab;

C++ will accept it the C way, but it's bad style unless you named a struct the same as a variable (which is bad style for a different reason).

To copy an array of structures, use a for loop and simple assigments:

struct student m_stuTab[NB_STU];
struct student temp_stuTab[NB_STU];

for (size_t i = 0; i < NB_STU; i++) {
    temp_stuTab[i] = m_stuTab[i];
}

This is the preferred solution for both C and C++. If you insist on using memcpy , you could write:

memcpy(temp_stuTab, m_stuTab, sizeof(*temp_stuTab) * NB_STU);

But it would not invoke the copy constructors nor the assignment overloaded functions in C++ and the size is easy to miscalculate. Good compilers will generate the same code for both approaches when possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM