【发布时间】:2021-11-09 22:45:32
【问题描述】:
我在通过结构对象初始化结构中的字符数组时遇到问题
#include <iostream>
#include <string.h>
using namespace std;
struct emp
{
int age;
char name[10];
};
int main()
{
struct emp v[2];
List item
v[0].age = 9;
v[0].name[] = "name1"; <-this is where i am getting error
v[1].age = 10;
v[1].name[]= "name2"; <-this is where i am getting error
for (int i = 0; i < 2; i++)
{
cout << v[i].age << " " << v[i].name<<endl;
}
return 0;
}
【问题讨论】:
-
您遇到了什么问题?请不要混淆 c 和 c++,它们是两种不同的语言。您的代码是 c++,而不是 c。您包含一个 c 标头,标头的 c++ 变体称为
<cstring>,但我认为您无论如何都没有使用它的任何内容 -
List item真的是这段代码的一部分吗? -
因为这是c++,你有什么理由不使用
std::string? -
你为什么要把 Emp.name 当作 char[]
-
这种对数组的赋值根本不适合该语言,无论是 C 还是 C++。不过,您可以提供 initialiser:
emp v[] = { {9, "name1"}, {10, "name2"} };.
标签: c++ arrays struct assignment-operator string-literals