![](/img/trans.png)
[英]how to properly pass a struct pointer having a function member in pthread_create in c++
[英]Struct having pointer to member in C++, How to access it
好的,这是我的代码。 我有一个名为 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;
}
使用 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;
}
或者,如果您想使用 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;
}
您在源代码中输入的任何文字字符串值(例如"james"
)根据定义都是const char*
值, const
意味着它不能在程序运行时更改。 在您的类中, name
成员被声明为char*
类型,它不是const
,因此可能会在运行时更改。 编译器不会让你到指定const char*
值类型变量char*
保持不变那种类型的价值const char*
不得修改。 (当然,反过来也可以;您可以将char*
值分配给const char*
类型的变量。
为了解决这个问题,字符最少,你必须改变char* name
来const char* name
在你的employee
结构定义。 但是,我同意最好的做法是将其更改为std::string
成员,如@Hamza.S 在他们的回答中所列出的那样。 std::string
类有一个赋值运算符,它用一个const char*
值构建它,所以他们的答案中的james.name = "james"
行基本上将std::string
设置为等于const char*
值"james"
。
如果你热衷于使用 char*,你可以这样做:
#include <iostream>
#include <string.h>
#include <stdlib.h>
struct employee {
char *name;
int age;
};
int main() {
employee james;
james.age=12;
james.name = (char *)malloc(sizeof(char) * 10);
strcpy(james.name, "James");
std::cout << james.name << std::endl;
return 0;
}
否则你可以像这样在你的结构中使用 std::string :
#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;
}
您可以尝试使用 strcpy
strcpy(james.name, "james");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.