我有一个包含名为char * text的成员的结构。在我从结构中创建了一个对象之后,如何将文本设置为字符串?
答案 0 :(得分:5)
如果你的结构是
struct phenom_struct {
char * text;
};
你分配它
struct phenom_struct * ps = malloc (sizeof (phenom_struct));
然后检查ps
的值不是NULL(零),这意味着“失败”,你可以将文本设置为这样的字符串:
ps->text = "This is a string";
答案 1 :(得分:1)
你的struct成员实际上不是一个字符串,而是一个指针。您可以通过
将指针设置为另一个字符串o.text = "Hello World";
但是你必须要小心,字符串必须至少和对象一样长。使用malloc如其他答案所示是一种可行的方法。在许多情况下,更希望在struct中使用char数组;即代替
struct foobar {
...
char *text;
}
使用
struct foobar {
...
char text[MAXLEN];
}
这显然要求你知道字符串的最大长度。
答案 2 :(得分:0)
typedef struct myStruct
{
char *text;
}*MyStruct;
int main()
{
int len = 50;
MyStruct s = (MyStruct)malloc(sizeof MyStruct);
s->text = (char*)malloc(len * sizeof char);
strcpy(s->text, "a string whose length is less than len");
}
答案 3 :(得分:0)
示例:
struct Foo {
char* text;
};
Foo f;
f.text = "something";
// or
f.text = strdup("something"); // create a copy
// use the f.text ...
free(f.text); // free the copy