Question

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

Was it helpful?

Solution

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

OTHER TIPS

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.

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

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top