views:

79

answers:

4

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?

A: 
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");
}
Amarghosh
+3  A: 

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";
Kinopiko
A: 

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
Nick D
Syntax errors everywhere...its "struct Foo f;" and "f.text"
ammoQ
@ammoQ, ooooops. Thanks.
Nick D
+1  A: 

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.

ammoQ