This code accepts an array of struct Student and then displays it, using a pointer. The code uses not so common approach. The common approach is shown in single-line comments within this code itself.
However, there seems some problem with this approach because the correct value of "percentage" is not displayed. Can anyone tell me what is the cause of this problem?
#include<stdio.h>
struct Student
{
char grade;
int rollNumber;
float percentage;
};
typedef struct Student Student;
void acceptArray(Student*);
void displayArray(Student*);
int main()
{
Student myFriends[3];
Student* p = myFriends;
acceptArray(p);
displayArray(p);
}
void acceptArray(Student* p)
{
int i = 0;
for(i = 0; i < 3; i++)
{
printf("\nEnter grade, roll number, and percentage:\n");
scanf(" %c %d %f",
(p + i),
//&(p + i)->grade
//&p[i].grade
( (Student*)((unsigned int)p + sizeof(char)) + i ),
//&(p + i)->rollNumber
//&p[i].rollNumber
( (Student*)((unsigned int)p + sizeof(char) + sizeof(int)) + i )
//&(p + i)->percentage
//&p[i].percentage
);
}
}
void displayArray(Student* p)
{
int i = 0;
for(i = 0; i < 3; i++)
{
printf("\nGrade is : %c.", *(p + i));
//(p + i)->grade
//p[i].grade
printf("\nRoll number is: %d.", *( (Student*)((unsigned int)p + sizeof(char)) + i ));
//(p + i)->rollNumber
//p[i].rollNumber
printf("\nPercentage is : %.1f.", *( (Student*)((unsigned int)p + sizeof(char) + sizeof(int)) + i ));
//(p + i)->percentage
//p[i].percentage
}
}