【发布时间】:2013-11-12 21:21:49
【问题描述】:
好的,首先我将解释我的任务。对于这个任务,我必须使用我没有问题的动态内存分配。我遇到的问题是找出完成任务的正确方法。对于我的作业,我需要创建一个程序,提示用户输入他们有多少学生,然后询问以下信息;学生证、生日和电话号码。我需要使用循环来提示用户输入所有学生信息。我需要创建一个循环来扫描所有学生 ID,并使用他们的生日找到年龄最大的学生(循环必须能够扫描超过 3 个学生)。
这是我的代码,我从你们那里得到了一些建议,甚至是一些代码,但是当它进入 for 循环时它不允许我输入学生信息,它只是结束程序。帮助
谢谢。
#include <stdio.h>
#include <stdlib.h>
struct studentDataType
{
int studentID;
int year;
int month;
int day;
long long phone;
};
int main (void)
{
int * studentData= NULL;
int * studentDataType;
int students;
int studentID;
int year;
int month;
int day;
long long phone;
printf("How many students are you entering records for:\n");
scanf("%d", &students);
studentData= malloc((sizeof(int)*students));
struct studentDataType *studentRecords = malloc(sizeof(struct studentDataType) * students);
for (int i = 0 ; i != students ; ++i) {
printf("Enter information for student %d\n", i+1);
struct studentDataType * s = &studentData[i];
scanf("%d%d%d%d%d", &(s->studentID), &(s->year), &(s->month), &(s->day), &(s->phone));
}
}
【问题讨论】:
-
一方面,所写的
struct studentDataType * s = &studentData[i];甚至不会编译,因为studentData是一个指向int 的指针,显然s是不是。所以标题中你的问题的直接答案是:“因为代码不会编译。”并且输入格式字符串中的最后一个%d与s->phone的数据类型不匹配,后者是long long,因此假设您修复了损坏的编译,您在那里有未定义的行为。 -
如果你不能说我对此很陌生,那么请你给我一个解决方案。
-
由于代码无法编译,请查看错误输出以了解有关错误的信息。
-
从 for 循环中删除整数 i 的声明,并使其高于 for 循环(您已声明其他变量的地方),这些类型的初始化仅在 C99 标准中允许。
-
“给我一个解决方案” - 嗯.. 如果你想要解决的唯一“新”问题就是向人们寻求解决方案,我想我可以做到。我相当肯定这不是你所学课程的既定目标。我已经指出了两个重要问题。处理这些。在this, question、this question 和当前问题之间,你已经吃到了大部分的勺子。