开发者

How to set a struct member of type string

I have a struct which contains a member called char *text. 开发者_Go百科 After I've created an object from the struct, then how do I set text to a string?


If your struct is like

 struct phenom_struct {
    char * text;
 };

and you allocate it

 struct phenom_struct * ps = malloc (sizeof (phenom_struct));

then after checking the value of ps is not NULL (zero), which means "failure", you can set text to a string like this:

 ps->text = "This is a string";


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");
}


Your struct member is not really a string, but a pointer. You can set the pointer to another string by

o.text = "Hello World";

But you must be careful, the string must live at least as long as the object. Using malloc as shown in the other answers is a possible way to do that. In many cases, it's more desirable to use a char array in the struct; i.e. instead of

struct foobar {
    ...
    char *text;
}

use

struct foobar {
    ...
    char text[MAXLEN];
}

which obviously requires you to know the maximum length of the string.


Example:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜