[英]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++;
循環內。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.