【问题标题】:Do I need to create three separate arrays for my assignment?我需要为我的作业创建三个单独的数组吗?
【发布时间】:2013-11-12 17:14:39
【问题描述】:

好的,首先我将解释我的任务。对于这个任务,我必须使用我没有问题的动态内存分配。我遇到的问题是找出完成任务的正确方法。对于我的作业,我需要创建一个程序,提示用户输入他们有多少学生,然后询问以下信息;学生证、生日和电话号码。我需要使用循环来提示用户输入所有学生信息。我需要创建一个循环来扫描所有学生 ID,并使用他们的生日找到年龄最大的学生(循环必须能够扫描超过 3 个学生)。

这是我的代码,我还没有做太多,因为我不确定从哪里开始。我已经设置了动态内存分配,但我不知道如何处理其余部分。请帮帮我。

谢谢。

#include <stdio.h>
#include <stdlib.h>

int main (void)
{
int * studentData= NULL;

int students;
printf("How many students are you entering records for:\n");
scanf("%d", &students);

studentData=(int*)malloc((sizeof(int)*students));
}

【问题讨论】:

标签: c arrays loops dynamic-memory-allocation


【解决方案1】:

你可以定义一个结构:

//Define a type, such as int, char, double...
typedef struct studentDataType {
    int ID;
    int birthDateDay;
    int birthDateMonth;
    int birthDateYear;
    int phoneNumber;
};

然后创建一个数组,其中每个元素的类型都是 studentData:

//Create an array, where each element is of type studentData
studentDataType *studentData = (studentDataType *)malloc(numberOfStudents * sizeof(studentData));

然后循环遍历它们:

for (int i = 0 ; i < numberOfStudents ; ++i) {
    printf("%i %i %i\n", studentData[i].ID, studentData[i].phoneNumber);
}

【讨论】:

  • struct 声明中缺少分号。
  • cout 是 C++,而不是 C。您必须使用 printf
  • 对不起,使用 printf,cout 是 C++。
  • 我对 arrayOfStudents 所引用的内容也有点困惑。
  • arrayOfStudents 是包含数据的数组(在您的代码中,我假设 studentData 与我的 arrayOfStudents 相同)。
【解决方案2】:

使用以下结构。您可以将年、月和日设为单独的字段。快速入门会更简单:

struct Student
{
    int studentID; 
    int year;
    int month;
    int day;
    long long phone; // phone is too large for 32 int
};

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-25
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 2013-02-02
    相关资源
    最近更新 更多