【发布时间】:2022-01-18 09:05:05
【问题描述】:
我正在练习 c,我刚刚学会了如何分配整数和创建结构,我遇到了箭头运算符,我不知道如何应用它,我研究了一下,现在我知道 a->b 是与 (*a).b 相同,并且该箭头用于指针,我的问题是如何将此代码转换为使用箭头运算符,我尝试将成员从 int 更改为 int * 但它仍然不起作用。
#include <stdio.h>
#include <string.h>
struct student {
char name[10];
int chem_marks;
int maths_marks;
int phy_marks;
};
int main()
{
struct student ahmad;
struct student ali;
struct student abu_abbas;
strcpy (ahmad.name,"ahmad");
ahmad.chem_marks=25;
ahmad.maths_marks=50;
ahmad.phy_marks=90;
strcpy (ali.name,"ali");
ali.chem_marks=29;
ali.maths_marks=90;
ali.phy_marks=13;
strcpy (abu_abbas.name,"abu");
abu_abbas.chem_marks=50;
abu_abbas.maths_marks=12;
abu_abbas.phy_marks=80;
int ahmadavg=(ahmad.chem_marks+ahmad.maths_marks+ahmad.phy_marks)/3;
int aliavg=(ali.chem_marks+ali.maths_marks+ali.phy_marks)/3;
int abu_abbasavg=(abu_abbas.chem_marks+abu_abbas.maths_marks+abu_abbas.phy_marks)/3;
printf("%s ",ahmad.name);
printf("average:%d\n",ahmadavg);
printf("%s ",ali.name);
printf("average:%d\n",aliavg);
printf("%s ",abu_abbas.name);;
printf("average:%d\n",abu_abbasavg);
}
【问题讨论】:
-
您没有在代码中使用指针,因此任何使用
->运算符的尝试都是没有意义的(双关语不是有意的)。阅读学习材料中关于指针的章节。 -
您应该对使用
malloc和free的动态内存分配以及指针的一般工作方式进行一些研究。一个简单的例子是struct student *ahmad = malloc(sizeof(*ahmad);然后在任何你使用ahmad.whatever的地方,你现在都会使用ahmad->whatever,最后当你用完那个变量free(ahmad)时。您可以将成员更改为指针,但您需要为它们分配内存并在完成后释放它。 “它不起作用”不是有用的问题描述,您遇到问题的代码不是您问题中的代码。 -
@RetiredNinja 谢谢你的帮助,我知道我的代码没有使用箭头运算符,我想知道如果它使用箭头运算符,这段代码会是什么样子,因为我知道这个概念在它后面,但我不知道它是如何应用的。 ut 你帮了我很大的忙,谢谢。
-
@Jabberwocky 我知道指针,因此我尝试将成员更改为指针,我接受了其他评论的建议并尝试在我的代码中实现它,但它并没有完全起作用,我的问题是,是否可以通过简单地将成员或结构更改为使用 * 而不是 malloc/free 的指针来使用箭头运算符,我仍然不知道它们是什么,并且需要对它们进行一些研究。