将数组结构作为指针传递给函数并进行初始化

问题描述 投票:1回答:1

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

这是我的代码:

#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);
    }
}
c function structure pass-by-reference
1个回答
0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.