如何设置string类型的struct成员

neu*_*cer 1 c string struct pointers

我有一个结构,其中包含一个名为char*text的成员.从结构体创建对象后,如何将文本设置为字符串?

小智 5

如果你的结构是这样的

 struct phenom_struct {
    char * text;
 };
Run Code Online (Sandbox Code Playgroud)

你分配它

 struct phenom_struct * ps = malloc (sizeof (phenom_struct));
Run Code Online (Sandbox Code Playgroud)

然后检查后的值ps不是NULL(零),这意味着"失败",你可以将文本设置为这样的字符串:

 ps->text = "This is a string";
Run Code Online (Sandbox Code Playgroud)