I have a problem regarding initializing an structure array to function by passing it as a pointer. I tried to multiply the counter from the size of my struct to track the array struct address in my next initialization but it gives me wrong output. Can anyone help me ?
Here is my code:
#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);
}
}
Two changes are required.
(1) You are never incrementing the pointer in createStudent
. So replace the line *(ptr + counter*sizeof(struct student));
with ptr += counter
As ptr
is already a pointer of type struct student
, incrementing it by 1 automatically moves to next record.
(2) In displayStudent
too, you are never using the incrementing i
. So, after printf
statement, add ptr++;
within the loop.