在函数中将数组结构作为指针传递并初始化

passing array structure as pointer in function and initialize

我在通过将结构数组作为指针传递来初始化结构数组时遇到问题。我试图将计数器乘以我的结构大小以在我的下一次初始化中跟踪数组结构地址,但它给了我错误的输出。谁能帮帮我?

这是我的代码:

#include <stdio.h>
#pragma pack(1)

struct student {
    int idnum;
    char name[20];
};

void createStudent(struct student *);

int counter=0;

int main() {

    struct student s[2];
    int choice = 0;

    do {
        printf("\nMENU\n");
        printf("1.] Create student\n");
        printf("2.] Display student\n");
        printf("Enter choice: ");
        scanf("%d",&choice);

        switch(choice){
            case 1: createStudent(s);
                    break;
            case 2: displayStudent(s);
                    break;
        }
    }while(choice !=3);
    return 0;
}

void createStudent(struct student *ptr) {
    if(counter > 1) {
        printf("Array Exceed");
    }else {
        *(ptr + counter*sizeof(struct student));
        printf("The counter: %p\n",*(ptr + counter*sizeof(struct student)));

        printf("Enter ID NUM:");
        scanf("%d",&ptr->idnum);
        fflush(stdin);
        printf("\nEnter NAME:");
        scanf("%s",ptr->name);
        counter++;
    }


}

void displayStudent(struct student *ptr) {
    for(int i=0;i<counter;i++) {
        printf("\nStudent ID NUM: %d\t Student Name: %s",ptr->idnum,ptr->name);
    }
}

需要进行两项更改。
(1) 你永远不会增加 createStudent 中的指针。因此,将行 *(ptr + counter*sizeof(struct student)); 替换为 ptr += counter
由于 ptr 已经是类型 struct student 的指针,因此将其递增 1 会自动移动到下一条记录。

(2) 同样在 displayStudent 中,您永远不会使用递增的 i。因此,在 printf 语句之后,在循环内添加 ptr++;