[英]Dynamically allocating strings within a struct
If I have a struct defined as such:如果我有一个这样定义的结构:
typedef struct{
char a[];
}my_struct_t;
How do you allocate memory for a string with malloc()
such that it is stored in my_struct_t
?如何使用
malloc()
为字符串分配内存,使其存储在my_struct_t
?
Code could uses a flexible array member to store string in the structure.代码可以使用灵活的数组成员在结构中存储字符串。 Available since C99.
从 C99 开始可用。 It requires at least one more field in the
struct
.它至少需要在
struct
多一个字段。
As a special case, the last element of a structure with more than one named member may have an incomplete array type;
作为一种特殊情况,具有多个命名成员的结构的最后一个元素可能具有不完整的数组类型; this is called a flexible array member .
这称为灵活数组成员。 ... C11 §6.7.2.
... C11 §6.7.2。 18
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;
}
As exactly coded, the below is not valid C syntax.正如完全编码的那样,以下不是有效的 C 语法。 Of course various compilers offer language extensions.
当然,各种编译器都提供语言扩展。
typedef struct{
char a[];
}my_struct_t;
#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;
}
Array of 100 chars. 100 个字符的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.