【问题标题】:Dynamically allocating strings within a struct在结构中动态分配字符串
【发布时间】:2017-02-15 15:26:25
【问题描述】:

如果我有这样定义的结构:

typedef struct{

    char a[];

}my_struct_t;

如何为带有malloc() 的字符串分配内存,使其存储在my_struct_t 中?

【问题讨论】:

  • 这看起来很像char *,类型很有趣。

标签: c struct malloc realloc


【解决方案1】:

代码可以使用灵活的数组成员字符串存储在结构中。从 C99 开始可用。它至少需要struct 中的一个字段。

作为一种特殊情况,具有多个命名成员的结构的最后一个元素可能具有不完整的数组类型;这称为灵活数组成员。 ... C11 §6.7.2。 18

typedef struct fam {
  size_t sz;  // At least 1 more field needed. 
  char a[];   // flexible array member - must be last field.
} my_struct_t;

#include <stdlib.h>
#include <string.h>

my_struct_t *foo(const char *src) {
  size_t sz = strlen(src) + 1;

  // Allocate enough space for *st and the string
  // `sizeof *st` does not count the flexible array member field 
  struct fam *st = malloc(sizeof *st + sz);
  assert(st);

  st->sz = sz;
  memcpy(st->a, src, sz);
  return st;
}

按照完全编码,以下不是有效的 C 语法。当然,各种编译器都提供语言扩展。

typedef struct{
    char a[];
}my_struct_t;

【讨论】:

  • 这件事似乎很危险。我以前从未见过。很有趣。
  • @Secto Kia Older C 将使用最后一个成员作为char a[1];,因此该技术已经使用了几十年。较旧的技术存在对 C99 和 char a[];(对齐、sizeof struct、分析工具)感到满意的问题。就像 C 棚中的许多工具一样:为正确的工作使用正确的工具。
  • @SectoKia 注意:当最后一个数组元素不是char [] 时,通常使用malloc(sizeof *st + sizeof *(st-&gt;a) * N); 成语。
【解决方案2】:
#include <stdio.h>
#include <stdlib.h>

typedef struct {
     char* a;
} my_struct_t;


int main() 
{
    my_struct_t* s = malloc(sizeof(my_struct_t));
    s->a = malloc(100);
    // Rest of Code
    free(s->a);
    free(s);
    return 0;
}

100 个字符的数组。

【讨论】:

  • OP 请求“...为带有 malloc 的字符串分配内存,以便将其存储在 my_struct_t?” .这个答案可能符合 OP 的目标,但它不会将字符串 in 存储在结构中,而是存储指向 future 字符串的指针。
猜你喜欢
  • 1970-01-01
  • 2017-06-14
  • 2021-08-11
  • 1970-01-01
  • 2018-08-05
  • 1970-01-01
  • 2016-05-16
  • 2015-07-23
  • 1970-01-01
相关资源
最近更新 更多