C, Multi-Dimensional Arrays Exercise

孤人 提交于 2019-12-11 16:47:29

问题


My understanding of a 2d array is wrong. So I'll approach this question another way. Say I have the following variables.

int student_id[10], course_id[5];

int student_course[10][2];

There can only be 10 students. There can only be 5 courses. A student can only take 2 courses.

/*prompt user for student id*/

/*
say that the value for: 
student_id[0]=123
*/

/*prompt user for course id*/

/*
say that the value for:
course_id[0]=101
course_id[1]=102
course_id[2]=103
course_id[3]=104
course_id[4]=105
*/

What I want to print out is the
student_course[value_of_student_id][value_of_course_id].

So I thought of doing it this way:

int student_id[10], course_id[5], student_course[10][2]

int i, j, k;

for(i=0; i<10;i++){
    for(j=0; j<5; j++){

        /*prompt user for student id*/
        printf("Enter User ID: ");
        scanf("%d", &student_id);

        /*prompt user for course id*/
        printf("Enter Course ID: ");
        scanf("%d", &course_id);

        for(k=0; k<2; k++){
            student_course[i][j]=student_course[i][k];
        }

    }
}

If this is the wrong way, what is the correct way to get the results I want? A 3 dimensional array perhaps? I might not be ready for that yet.


回答1:


You could do it like this instead

typedef struct
{
  int student_id;
  int course_id[2];
} Student

Student Students[10];

then initialize the array with the student_id's and what courses he is attending



来源:https://stackoverflow.com/questions/22033207/c-multi-dimensional-arrays-exercise

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!