0

I don't understand how, the code below, homeroom.roster[0].lastname and (*homeroom.roster).lastname are the reference. When the code is run, both printf calls print out "Jones"

Specifically, I get that roster[0] and roster are the same address from how arrays work in C, but how are homeroom.roster[0].lastname and (*homeroom.roster).lastname equivalent? The asterisk is throwing me for a loop.

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

typedef struct {
    char firstname[22];
    char lastname[22];
} Student;

typedef struct {
    int size;
    Student roster[33];
} Class;

void main() {

  Class homeroom;
  strcpy(homeroom.roster[0].lastname,"Jones");
  printf("%s\n",homeroom.roster[0].lastname);
  printf("%s\n",(*homeroom.roster).lastname);
  
}

There's no pointer, and yet an asterisk works...how? Why?

LordBalls
  • 1
  • 1
  • 1
    `pointer[i]` is equivalent to `*(pointer+i)` so when `i == 0` it's the same as `*pointer`. – Barmar Mar 01 '23 at 23:46
  • And it doesn't have to be a real pointer. An array decays to a pointer to its first element in this context. So `*array` is the same as `array[0]` – Barmar Mar 01 '23 at 23:48
  • 1
    And, in fact, for any `x` that you can put a `*` in front of or a `[…]` after, `*x` is the same as `x[0]`. – Steve Summit Mar 01 '23 at 23:53

0 Answers0