好的,这是我的代码。我有一个名为employee的结构,它有一个成员char *名称。如何更改名称的值?
struct employee {
char* name;
int age;
};
int main()
{
struct employee james;
james.age=12; // this line is fine
james.name = "james"; // this line is not working
cout << james.name;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
使用std :: string代替char *指针,它将正常工作
#include <iostream>
#include <string>
struct employee {
std::string name;
int age;
};
int main() {
employee james;
james.age=12;
james.name = "james";
std::cout << james.name;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您想使用char *指针,则可以使用const char* name 它。
#include <iostream>
struct employee {
const char* name;
int age;
};
int main() {
employee james;
james.age=12;
james.name = "james";
std::cout << james.name;
return 0;
}
Run Code Online (Sandbox Code Playgroud)