我有一个关于通过传递结构体数组作为指针来初始化结构体数组的问题。我试图将计数器的大小乘以结构的大小,以在下一次初始化时跟踪数组的结构地址,但它给了我错误的输出。谁能帮我吗?
这是我的代码:
#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++;
。