[英]assign and allocate memory for a pointer inside a struct in C?
Suppose I have a struct: 假设我有一个结构:
struct b {
unsigned short num;
unsigned short size;
unsigned char *a;
};
I then declare a pointer that points to a struct
of b
: 然后,我声明一个指向
b
的struct
的指针:
struct b *foo=malloc(sizeof(struct b));
how do I allocate memory for foo
's a
and assign a
to point to a character string? 如何为
foo
的a
分配内存并分配a
指向字符串?
It's not that different, eg, to allocate the memory for the string hello
: 并没有什么不同,例如,为字符串
hello
分配内存:
char *hello = "hello";
foo->a = malloc(strlen(hello) + 1);
strcpy(foo->a, hello);
Actually, struct b *foo = malloc(sizeof *foo);
实际上,
struct b *foo = malloc(sizeof *foo);
already allocates enough space to accomodate a char pointer, so it depends on what you want to do with foo->a
(ps: because foo is a pointer, you need to use the indirection operator). 已经分配了足够的空间来容纳char指针,因此它取决于您要对
foo->a
进行什么操作(ps:因为foo是一个指针,因此需要使用间接操作符)。
If foo->a
(or, *(foo).a
) can be a constant string, you can simply do this: 如果
foo->a
(或*(foo).a
)可以是常量字符串,则可以简单地执行以下操作:
struct b *foo = malloc(sizeof *foo);
foo->a = "A constant string";
Note that, because this is (sort of) equivalent to: 请注意,因为这等效于:
const char *const_str = "this is read-only";
You can't change anything about the chars a
points to. 您不能更改有关指向字符
a
任何信息。 The member a
is assigned an address of a string constant in read-only memory. 成员
a
被分配一个只读存储器中的字符串常量的地址。 In short: 简而言之:
foo->a = "constant";
printf("%c%c%c\n", foo->a[0], foo->a[2], foo->a[4]);//prints cnt
foo->a[0] = 'C';//WRONG!
If you want to be able to change the string, use this: 如果您希望能够更改字符串,请使用以下命令:
foo->a = malloc(50 * sizeof *(foo->a)));
The sizeof
is optional here, since the size of char
is guaranteed to be size 1, always. sizeof
在这里是可选的,因为char
大小始终保证为1。
To assign/copy a string you use strcat
, strcpy
, memcpy
, strncat
, sprintf
and the like 要分配/复制字符串,请使用
strcat
, strcpy
, memcpy
, strncat
, sprintf
等
strcpy(foo->a, "constant");
printf("%c%c%c\n", foo->a[0], foo->a[2], foo->a[4]);//still prints cnt
foo->a[0] = 'r';
printf("%c%c%c\n", foo->a[0], foo->a[2], foo->a[4]);//still prints rnt
Now you can change the string a
points to, but as a result, you'll have to free this memory, too, when you're done with it: 现在,您可以更改字符串
a
点,但作为一个结果,你必须释放此内存,也当你用它做:
//wrong:
free(foo);//works, but won't free the memory allocated for foo->a
//better:
free(foo->a);
free(foo);
应该使用'foo-> a'(运算符->)
First you have to assign memory for foo by malloc, then it will contain the address of the inside pointer called "a". 首先,您必须通过malloc为foo分配内存,然后它将包含内部指针“ a”的地址。 When you have the memory address of "a" (not the "pointed to" but the address where the pointed to address is stored), you can store addresses there.
当您具有“ a”的内存地址(不是“指向”的地址,而是指向地址的存储地址)时,可以在其中存储地址。
so: 1. struct b *foo = malloc(...) 2. foo->a = malloc(...) 因此:1. struct b * foo = malloc(...)2. foo-> a = malloc(...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.