Search code examples
c++arraysstructure

How to copy char array of a structure into another char array of a structure?


#include <iostream>
using namespace std;

struct stud
{
    char name[10];
    int id;
};

int input(stud a[], int size)
{
    for(int i=1; i<=size; i++)
    {
        cout<<"name = ";
        cin>>a[i].name;
        cout<<"id = ";
        cin>>a[i].id;
    }
    cout<<endl;
    return 0;
}
int output(stud a[], int size)
{
    for(int i=1; i<=size; i++)
    {
        cout<<"name = "<<a[i].name<<" ";
        cout<<"id = "<<a[i].id<<" ";
    }
    cout<<endl;
    return 0;
}

int copy(stud a[], stud x[], int size)
{

    for(int i=1; i<=size; i++)
    {
        x[i].name=a[i].name; 
        x[i].id=a[i].id;
    }
    output(x,size);
    cout<<endl;
    return 0;
}

int main()
{

    struct stud s[3], x[3];
    input(s,3);
    output(s,3);
    copy(s,x,3);
    return 0;
}

In this program the statement in function copy x[i].name =a[i].name; is not copying contents from 1 structure object to another. I have tried to put this statement in for loop for(int j=1;j<=10;j++) x[i].name[j] =a[i].name[j]; but still not working. please suggest what should be changed or some alternatives for this. i'll be very thankful to you for this.

regards, umar


Solution

  • Either using a loop to copy each character in the name field or using thestrcpy function from <cstring> header works.

    int copy(stud a[], stud x[], int size) {
        for(int i = 1; i <= size; i++) {
            // for(unsigned j = 0; j < 10; j++) {
            //     x[i].name[j] = a[i].name[j];
            // }
            strcpy(x[i].name, a[i].name);
            x[i].id = a[i].id;
        }
        output(x, size);
        cout << endl;
        return 0;
    }
    

    But since you tagged this as c++, consider using std::string instead of a char array, unless you have a particular reason for using a char array. In that case x[i].name = a[i].name would have worked just fine and you could also use the standard algorithm library for copy. Also, using std::array instead of a raw C array for you "array of structures" might be a better option (does not degenerate into a pointer like a regular C array does).