指向结构的指针
我是指针的新手,并试图使用指向结构的指针。 但在第一次进入后,我的程序崩溃了。 请帮助我。
这是结构定义:
struct students{//structure students definition char name[20]; char RegNo[15]; char CourseUnit[10]; int score; char grade; };
等级不应由用户输入,而是由程序计算。
到目前为止,这是我写的代码:
int main()//start of main { struct students *myStudPtr,myStud[SIZE]; myStudPtr=&myStud[SIZE]; int i;//declare variables int count; printf("How many students do you want to deal with?\n"); scanf("%d",&i);//number of entries for(count=1;countname); printf("%s\t\t", myStudPtr->RegNo); printf("%s\t", myStudPtr->CourseUnit); printf("%d\t\t", myStudPtr->score); if(myStudPtr->score>100) { printf("Invalid\n"); } else if(myStudPtr->scorescorescorescorescore>70) { printf("A\n"); } else { printf("Invalid"); } return 0; }
请帮助。谢谢。
您有一个索引越界错误,导致运行时未定义的行为 :
myStudPtr = &myStud[SIZE]; // ^^^^^ // wrong
根据声明struct students myStud[SIZE];
,最大索引值可以是SIZE - 1
。 记住数组索引从0
开始。
编辑
据我所知,你已经声明了一个struct数组,并希望使用指向struct的指针从用户那里读取i
的学生信息。 但是你的代码中还有一些问题,例如在for循环中你总是访问相同的 struct元素:
for(count = 1; count <= i; count++) scanf("%s", &(*myStudPtr).name); // ^ // points to same struct element in array
每个scanf()
和printf()
语句中都存在此错误。
正确如下:
-
初始化指向数组中第一个元素地址的指针:
myStudPtr = &myStud[0]; // ^ first element at 0th index
-
通过指针,您可以通过以下两种方式之一访问struct的元素:
第一 :例如扫描学生的
score
值:scanf("%d", &myStudPtr[count].score);
注意:
[]
'数组下标运算符'的优先级高于.
'通过对象名称运算符选择成员',因此您不需要()
括号。 同样优先.
operator高于&
ampersand运算符,所以即使你不需要任何括号来获取地址(例如&(myStudPtr[count].score)
不需要)。第二 :使用指针和
->
运算符扫描学生的score
值:scanf("%d", &(myStudPtr + count)->score);
注意 :
+
plus运算符的优先级较低,因此我们需要括号来覆盖优先级。 并且->
成员选择的优先级通过指针运算符高于&
ampersand运算符所以这里你也不需要任何括号,如&((myStudPtr + count)->score)
。
重要说明:
-
您应该检查用户输入的
i
值必须小于SIZE
(strcut数组的大小),否则您的代码中可能有未定义的行为。 -
要读取字符串,请使用安全的
fgets()
函数而不是scanf来避免缓冲区溢出。 阅读: “使用scanf()
读取一行scanf()
不好?”
还有一点注意事项:
-
因为你是新的C程序员(我觉得)你应该阅读:缩进C编程它是一个学习缩进练习的快速教程。
-
你应该始终保持空间
,
并且;
使代码可读,出于同样的原因,像count<=i
这样的表达式应写成count <= i
。 比较你的for循环:for(count=1;count<=i;count++)
接下来我想建议你:
for(count = 1; count <= i; count++){ // code after one tab }
改进代码:
我还建议你改进if-else编码风格,你的if-else部分代码可以写成如下:
score = myStudPtr->score; if(0 <= score && score <= 100){ if(score > 70) printf("A"); if(60 <= score && score < 69) printf("B"); if(50 <= score && score < 59) printf("C"); if(40 <= score && score < 49) printf("D"); if(score < 40) printf("FAIL"); } else printf("Error: Invalid Entry!"); printf("\n");
- 我删除了许多
else
语句,而是使用了&&。 - 删除了多余的
{..}
大括号对。 - 使用本地
score
变量而不是myStudPtr->score
来保持代码看起来简单。 - 从每个
pritf
语句中删除\n
,而不是在最后添加一个新的printf
(不是很重要)。
最后一个错误
要打印每个学生记录,您需要一个新的循环,您可以调用printf()
函数并包含if-else逻辑来评估学生成绩。