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?
-
objects in C?, strings in C? I think you need to clarify your question a little bit more :)HyLian– HyLian2009-11-26 08:15:35 +00:00Commented 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.AnT stands with Russia– AnT stands with Russia2009-11-26 10:28:49 +00:00Commented Nov 26, 2009 at 10:28
4 Answers
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";
Comments
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.