Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to do I access an array of structs using ONLY pointers

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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;
}

>Solution :

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading