0

Good evening/morning/day/afternoon, everyone. I am presently having a bit of an issue with my code. I am trying to make an array of structs called student, and am having issues figuring out how to point from one to the next in the array. Any guidance on the matter would be much appreciated.

main.c

int main()
{

int n_students = 0;
struct student students[1000];
int closebool = 0;
int IDnum; 
int k;
char buffer[101];
char *studentName_tmp;

    do
    {
        scanf("%d", &operation_num);
        switch (operation_num)
        {
            case 0 :
            {

                closebool = 1;
                break;

            }
            case 1 :
            {
                scanf("%d %s", &IDnum, buffer);
                studentName_tmp = (char *) malloc (strlen(buffer)+1);
                strcpy (studentName_tmp, buffer);
                n_students = insert(students, n_students, IDnum, studentName_tmp);
                printf ("%d %s\n", students[n_students].ID, students[n_students].name);
                n_students++;

                break;
            }
        }
    }  while (closebool != 1);
return 0;
} 

student.c

int insert(struct student array[], int numberof_students, int IDnum, char *student_name)
{
    array[numberof_students].ID = IDnum;
    array[numberof_students].name = student_name;

    return 0;
}

This is the input and output I expect to see: (input input output, in this case)

1, 123 fred, 123 fred, 1, 234 george, 234 george, 1, 345 henry, 345 henry,

However I see this:

1, 123 fred, 123 fred, 1, 234 george, 123 fred, 1, 345 henry, 123 fred,

4

2 回答 2

0

insert总是返回 0,但是你使用它的返回值的方式main意味着你希望它返回新插入的索引student,即numberof_students.

于 2013-05-02T00:27:31.847 回答
0

每次增加 n_students++ 时,实际上都是在将其设为 1。因为在成功插入()之后,n_students 会从该函数返回值,在您的情况下为 0(返回 0),所以到目前为止您增加的任何值都是回到零。

要获得您想要的结果,只需进行以下更改

insert(students, n_students, IDnum, studentName_tmp);

现在您没有在 n_students 中收集价值,因此 n_students 每次都会增加(两者之间不会为零)。

于 2013-05-02T06:41:03.700 回答