포인터로 전달하여 구조 배열을 초기화하는 데 문제가 있습니다. 다음 초기화에서 배열 구조체 주소를 추적하기 위해 구조체 크기에서 카운터를 곱하려고 시도했지만 잘못된 출력을 제공합니다. 누구든지 나를 도울 수 있습니까?
내 코드는 다음과 같습니다.
#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
As ptr
is already a pointer of type으로 바꾸고 struct student
1 씩 증가 시키면 자동으로 다음 레코드로 이동합니다.
(2) displayStudent
역시 증분을 사용하지 않습니다 i
. 따라서 printf
문 후 ptr++;
루프 내에 추가 하십시오.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다