文字列型の構造体メンバーを設定する方法
質問
char * textというメンバーを含む構造体があります。構造体からオブジェクトを作成した後、テキストを文字列に設定するにはどうすればよいですか
解決
構造体が次のような場合
struct phenom_struct {
char * text;
};
そしてあなたはそれを割り当てます
struct phenom_struct * ps = malloc (sizeof (phenom_struct));
その後、 ps
の値がNULL(ゼロ)でないことを確認した後、「失敗」を意味するため、次のような文字列にテキストを設定できます。
ps->text = "This is a string";
他のヒント
構造体のメンバーは実際には文字列ではなく、ポインターです。ポインタを別の文字列に設定するには、
を使用しますo.text = "Hello World";
ただし、注意する必要があります。文字列は少なくともオブジェクトと同じ長さでなければなりません。他の回答に示されているようにmallocを使用することは、そのための可能な方法です。多くの場合、構造体でchar配列を使用する方が望ましいです。つまり、
の代わりにstruct foobar {
...
char *text;
}
使用
struct foobar {
...
char text[MAXLEN];
}
明らかに、文字列の最大長を知る必要があります。
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");
}
例:
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
所属していません StackOverflow