如何将一个结构的字符数组复制到结构的另一个字符数组中?

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

本文关键字:字符 数组 结构 复制 另一个 一个      更新时间:2023-10-16
#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;
}

在此程序中,函数复制x[i].name =a[i].name;中的语句不会将内容从一个结构对象复制到另一个结构对象。我试图将此语句放入循环for(int j=1;j<=10;j++) x[i].name[j] =a[i].name[j];但仍然不起作用。 请建议应该更改的内容或一些替代方案。 为此,我将非常感谢您。

问候 奥马尔

使用循环复制name字段中的每个字符或使用标头中的strcpy函数<cstring>都可以。

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

但是由于您将其标记为c++,请考虑使用std::string而不是 char 数组,除非您有特殊原因使用 char 数组。在这种情况下,x[i].name = a[i].name可以正常工作,您也可以使用标准algorithm库进行复制。此外,使用std::array而不是原始 C 数组作为"结构数组"可能是一个更好的选择(不会像常规 C 数组那样退化为指针(。

Evrey 单个循环是错误的,因为C++数组从零开始。所以不是

for(int i=1; i<=size; i++)

相反

for(int i=0; i<size; i++)

不能通过写入a = b;来复制数组。由于您的数组实际上是字符串,因此有一个内置的函数strcpy来复制字符串。

strcpy(x[i].name, a[i].name);

如果使用=复制结构,则将复制该结构内的char数组。您不需要再执行任何操作。

#include <iostream>
using namespace std;
typedef struct{
char name[10];
} type_t;
int main() {
type_t a = {"hihi"};

type_t b;
b = a;

a.name[0] = 'a';

cout<<a.name<<endl;
cout<<b.name<<endl;

return 0;
}

输出: 爱姬 希希

IDONE: https://ideone.com/Zk5YFd