Home > Software design >  How to do I access an array of structs using ONLY pointers
How to do I access an array of structs using ONLY pointers

Time:07-26

I am trying to access the students array of structs and modify a "Student" at a given index (using a for loop).

However, I am trying to access it using only a pointer, not like this:
students[currStudent].theory = thoeryGrade;

But something along the lines of:
*(studentPtr currStudent).practical = practicalGrade;
Note: The above line doesn't compile.

#include <stdlib.h>
#include <stdio.h>

typedef struct Student
{
    double theory;
    double practical;
} Student;

int main()
{
    Student students[50];
    const int numStudents;
    int thoeryGrade, practicalGrade = 0;
    Student *studentPtr = students;

    printf("Enter number of students: ");
    scanf("%d", &numStudents);

    while (1)
    {
        for (int currStudent = 0; currStudent < numStudents; currStudent  )
        {
            printf("Enter theory average of student %d: ", (currStudent   1));
            scanf("%d", &thoeryGrade);

            printf("Enter practical average of student %d: ", (currStudent   1));
            scanf("%d", &practicalGrade);

            students[currStudent].theory = thoeryGrade;
            *(studentPtr   currStudent).practical = practicalGrade;
            printf("\n");
        }
        for (int currStudent = 0; currStudent < numStudents; currStudent  )
        {
            printf("Student # %d -> Theory: %.2f", (currStudent   1), students[currStudent].theory);
            printf("\n");
            printf("Student # %d -> Practical %.2f", (currStudent   1), students[currStudent].practical);
            printf("\n\n");
        }
    }

    return 0;
}

CodePudding user response:

The . operator has higher precedence than * (dereference), so you need to enclose the expression *(studentPtr currStudent) in brackets.

(*(studentPtr   currStudent)).practical = practicalGrade;

Alternatively, use the -> operator to directly access a member on the pointer.

(studentPtr   currStudent)->practical = practicalGrade;
  • Related