jjkl
jjkl

Reputation: 403

Why do we not use an indirection operator when trying to access element of an array using a pointer?

I have a program that asks for a number of students and then for each of their first, last names and studentID. I'm attempting to print each of the values that are stored in the array of students. However, I get an error on the line printf("%d\n", *(students+i)->studentID); of Indirection requires pointer operand ('int' invalid).

I tried changing the line to printf("%d\n", (students+i)->studentID); and it seems to work. Why is this happening and why don't we need to do this for the print statements above that are printing characters? Thanks

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

typedef struct Students {
    char firstName[20];
    char lastName[20];
    int studentID;
} Student;

void printRecords(Student *students, int size){

    for(int i = 0; i < size; i++){
        printf("%c\n", *(students+i)->firstName);  // prints
        printf("%c\n", *(students+i)->lastName);   // prints
        printf("%d\n", *(students+i)->studentID);  // does not print

     }
}

int main(int argc, const char * argv[]) {

    int number_of_records;

    printf("Please enter the number of records you would like to add:\n");
    scanf("%d", &number_of_records);

    Student *S;
    S = (Student*)malloc(sizeof(Student) * number_of_records);

    for(int i = 0; i < number_of_records; i++){
        printf("First name of student %d\n", i+1);
        scanf("%s/n", S[i].firstName);

        printf("Last name of student %d\n", i+1);
        scanf("%s/n", S[i].lastName);

        printf("StudentID of student %d\n", i+1);
        scanf("%d/n", &S[i].studentID);
    }

    printRecords(S, number_of_records);
}

Upvotes: 0

Views: 315

Answers (3)

0___________
0___________

Reputation: 68013

*(students+i)->studentID is an equivalent of *((students+i)->studentID)

You try to dereference the integer and you get the compile error.

The first compiles ok because

*(students+i)->firstName is the same as *((students+i)->firstName) and the member firstName is an array which decays to the pointer of the char * type. You can of course dereference pointers.

Upvotes: 1

Chris Dodd
Chris Dodd

Reputation: 126518

-> is an (implicit) indirection operator -- a->b is the same as (*a).b. So when you write

*(students+i)->studentID

that's the same as

*(*(students+i)).studentID

with TWO indirection operations.

Upvotes: 1

Code-Apprentice
Code-Apprentice

Reputation: 83577

You can use the indirection operator here, but then you use the member operator . instead of ->:

printf("%d\n", (*(students+i)).studentID);

This is semantically the same as

printf("%d\n", (students+i)->studentID);

Upvotes: -1

Related Questions