2

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?

2
  • objects in C?, strings in C? I think you need to clarify your question a little bit more :) Commented Nov 26, 2009 at 8:15
  • @HyLian: Objects in C? Yes, in C all data in storage is referred to as "objects". Strings in C? There are strings in C, of course. Commented Nov 26, 2009 at 10:28

4 Answers 4

5

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";
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.