【问题标题】:How to set a struct member of type string如何设置字符串类型的结构成员
【发布时间】:2009-11-26 08:12:11
【问题描述】:

我有一个结构,其中包含一个名为 char *text 的成员。从结构创建对象后,如何将文本设置为字符串?

【问题讨论】:

  • C 中的对象,C 中的字符串?我认为您需要进一步澄清您的问题:)
  • @HyLian:C 中的对象?是的,在 C 中,存储中的所有数据都称为“对象”。 C中的字符串?当然,C 中有字符串。

标签: c pointers string struct


【解决方案1】:

如果你的结构是这样的

 struct phenom_struct {
    char * text;
 };

然后你分配它

 struct phenom_struct * ps = malloc (sizeof (phenom_struct));

那么在检查ps的值不是NULL(零)后,这意味着“失败”,您可以将文本设置为这样的字符串:

 ps->text = "This is a string";

【讨论】:

    【解决方案2】:

    你的结构成员实际上并不是一个字符串,而是一个指针。您可以通过

    将指针设置为另一个字符串
    o.text = "Hello World";
    

    但是你必须小心,字符串必须至少和对象一样长。如其他答案所示使用 malloc 是一种可能的方法。在许多情况下,更希望在结构中使用 char 数组;即代替

    struct foobar {
        ...
        char *text;
    }
    

    使用

    struct foobar {
        ...
        char text[MAXLEN];
    }
    

    这显然需要你知道字符串的最大长度。

    【讨论】:

      【解决方案3】:
      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");
      }
      

      【讨论】:

        【解决方案4】:

        例子:

        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
        

        【讨论】:

          猜你喜欢
          • 2021-07-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-02-26
          • 2013-03-12
          • 1970-01-01
          相关资源
          最近更新 更多