gpt4 book ai didi

c - 令人困惑的结构提示

转载 作者:行者123 更新时间:2023-11-30 17:20:53 25 4
gpt4 key购买 nike

我正在学习 C 语言的结构,有一些技巧让我困惑所以如果我们有一个像这样的结构

struct Person{
char* name;
int age;
int weight;
int height;
};

现在它是一种复合数据类型,我可以像其他数据类型一样处理它。当我指向这个结构时

struct Person pointer=malloc(sizeof(Person)); 

现在 c 指向内存中的一个地址,其大小如果我的问题是 struct

A)真的知道 Person 由 4 个名为 name、age、weight、height 的变量组成,并将该实体复制到指针指向的新位置吗?

B) 这两种语法有什么区别?

struct Person *pointer=(Person*)malloc(sizeof(Person));
struct Person *pointer=malloc(sizeof(Person));

C)我不熟悉这个函数减速语法,所以有人可以帮我解释一下吗(函数名称是一个指针)?

struct Person *Person_create(char* name, int age, int height, int   weight){...}

最佳答案

问题A:

is really c know that Person consists of 4 variable with names name,age,weight,height and make copy to this entity to new place which pointer points to ?

答案:

问题第一部分的答案是"is",但我会将其改写为C 编译器知道...

问题的第二部分我不清楚。我不确定你在问什么。

问题B:

what is the difference in this two syntax ?

struct Person *pointer=(Person*)malloc(sizeof(Person));
struct Person *pointer=malloc(sizeof(Person));

答案:

如果你使用

 #include <stdlib.h>

在 .c 文件的顶部,两者是相同的。如果你不这样做,那么

 struct Person *pointer=(Person*)malloc(sizeof(Person));

有可能隐藏错误。请参阅Do I cast the result of malloc?了解更多详情。

问题C:

i'm not familiar with this function deceleration syntax so can any one clear up it to me (name of function is an pointer) ?

struct Person *Person_create(char* name, int age, int height, int   weight){...}

答案:

如果您想使用 malloc 系列函数从堆中分配 struct Person 类型的对象并返回指向已分配对象的指针,则上述语法是正确的。

您还可以选择返回使用堆栈内存定义的对象。

 struct Person Person_create(char* name, int age, int height, int   weight){...}

您选择哪一个完全取决于您自己。您必须确保当您使用对象的堆内存时,您必须记住在指针上调用free()。否则,你的程序将泄漏内存。

关于c - 令人困惑的结构提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28402196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com