【发布时间】:2017-02-15 15:26:25
【问题描述】:
如果我有这样定义的结构:
typedef struct{
char a[];
}my_struct_t;
如何为带有malloc() 的字符串分配内存,使其存储在my_struct_t 中?
【问题讨论】:
-
这看起来很像
char *,类型很有趣。
如果我有这样定义的结构:
typedef struct{
char a[];
}my_struct_t;
如何为带有malloc() 的字符串分配内存,使其存储在my_struct_t 中?
【问题讨论】:
char *,类型很有趣。
代码可以使用灵活的数组成员将字符串存储在结构中。从 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;
【讨论】:
char a[1];,因此该技术已经使用了几十年。较旧的技术存在对 C99 和 char a[];(对齐、sizeof struct、分析工具)感到满意的问题。就像 C 棚中的许多工具一样:为正确的工作使用正确的工具。
char [] 时,通常使用malloc(sizeof *st + sizeof *(st->a) * N); 成语。
#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 个字符的数组。
【讨论】:
my_struct_t?” .这个答案可能符合 OP 的目标,但它不会将字符串 in 存储在结构中,而是存储指向 future 字符串的指针。