Shaan
Shaan

Reputation: 25

Copy an element of struct array to another struct of same types

If there is a structure:

struct Student // Student structure to store student's records
{
int rollno; // student rollno
string name; // student name
string address; // address
int pno; // phone number
};

and int main() contains

int main()
{
Student *s;
s= new Student [10];
}

Then how can we assign a struct to a different struct of same types?

void arrange()
{
Student *p= new Student;
//    int temp;
    for (int i=0; i<10; i++)
    {
        for (int j=0; j<10; j++)
        {
            if (i != j)
            {
                if (s[i].rollno > s[j].rollno)
                {
                    p = s[i];
                    s[i] = s[j];
                    s[j] = p;
                }
             }
        }
    }

Upvotes: 0

Views: 86

Answers (2)

hivert
hivert

Reputation: 10667

If you declare p as a pointer to a student then the struct is accessed by *p. So you should write:

*p = s[i];
s[i] = s[j];
s[j] = *p;

However, I don't think having a pointer is of any use here. Just write

Student p;

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227390

Than how can we assign a struct to a different struct of same types

Just copy construct it:

int main()
{
    Student s[10]; // array of 10 students
    Student student = s[5]; // copy of 6th element of array
}

You are over-complicating things with all those pointers.

Upvotes: 1

Related Questions