提问人:Nikhil 提问时间:10/18/2022 更新时间:10/18/2022 访问量:176
结构的动态内存分配和函数传递
Dynamic memory allocation of structure and passing it in function
问:
我对指针和结构有些困惑。下面是小代码片段,请帮我更正一下。如何在函数中传递动态分配的结构?
struct xxx{
int x1;
int x2'
}
struct xxx function1(struct xxx *x)
{
struct xxx *B;
B = (struct xxx*)malloc(sizeof(struct xxx));
return B
}
int main()
{
struct xxx *A;
struct xxx *B;
A = (struct xxx*)malloc(sizeof(struct xxx));
B = (struct xxx*)malloc(sizeof(struct xxx));
B = function(A);
return 0;
}
答:
1赞
NoDakker
10/18/2022
#1
我尝试了您的代码,并执行了一些清理,因为它无法编译,然后添加了一些示例代码以赋予自定义函数一些含义。下面是一个示例代码片段,扩展了结构程序的功能。
#include <stdio.h>
#include <stdlib.h>
struct xxx{
int x1;
int x2;
}; /* You were missing the semicolon */
struct xxx* function1(struct xxx* x) /* Needed the pointer reference for the return value */
{
struct xxx *B;
B = (struct xxx*)malloc(sizeof(struct xxx));
B->x1 = x->x1 + 1; /* Do something to initialize the new structure using data from the input strucuter */
B->x2 = x->x2 + 1;
return B;
}
int main()
{
struct xxx *A;
struct xxx *B;
A = (struct xxx*)malloc(sizeof(struct xxx));
A->x1 = 234;
A->x2 = 65535;
//B = (struct xxx*)malloc(sizeof(struct xxx)); /* No need to do this as will get an allocated structure from the function */
B = function1(A);
printf("A structure values: x1: %d, x2: %d\n", A->x1, A->x2);
printf("B structure values: x1: %d, x2: %d\n", B->x1, B->x2);
return 0;
}
以下是一些关键点。
- 首先,我在结构定义的末尾添加了一个缺失的分号。我不知道这是否只是在提交您的代码示例时遗漏了,但这是必需的。否则,程序将无法编译。
- 接下来,由于 function1 应该返回一个结构指针,因此签名从“struct xxx function1(struct xxx* x)”更正为“struct xxx* function1(struct xxx* x)”
- 函数中的代码很好,但实际上并没有做任何事情,因此添加了一些示例代码来提供输入结构 (xxx) 的用法,从而为函数中创建的结构提供一些数据。
- 在 main 函数中,指针“B”的分配内存被停用,因为该指针将使用结构及其从函数调用中分配的内存进行更新。如果该行保持活动状态,则实际上会删除对指针“B”的初始分配内存的引用,从而导致内存泄漏。
因此,考虑到这一点,以下是运行此示例时终端的示例输出。
@Una:~/C_Programs/Console/StructureB/bin/Release$ ./StructureB
A structure values: x1: 234, x2: 65535
B structure values: x1: 235, x2: 65536
希望这能为定义和使用结构提供一些额外的见解。
评论
0赞
Nikhil
10/19/2022
非常感谢您通过清晰的解释消除了我的一些疑虑。诚挚的问候,Nikhil Ganapathy
下一个:为什么总有例外?
评论
struct xxx{ int x1; int x2' }
不编译。