0
struct student ST[] = {{1, "John", 60}, {2, "Jack", 40}, {3, "Jill", 77}, {4, “Sam”, 78 }, {5,
“Dean”, 80}};
struct student *ptr = ST; //&ST is illogical
printf("\n%d\n", *ptr); //prints 1

This is taken from my university textbook. Both ST and &ST return a considerably large number which I presume to be the address of the structure variable. But according to my intuition, ST shouldn't work. ST doesn't return an address right? How is it getting stored? Why is &ST stated as illogical?

  • 3
    ST isn't a structure, it is an _array_ of structures – Mat Jun 03 '22 at 05:45
  • So calling an array will give the address of the first element right? Thank you I think I got it :) – user18025483 Jun 03 '22 at 05:49
  • In most contexts, the array name (`ST` in this case) _decays_ to the address of its first element. Such is the case with `struct student *ptr = ST;`, so `ptr` points to the address of the first element of `ST`(that is, `{1,"John",60}`). From the initialization of `ST`, we can see the first element is a number (dunno what type, however). `%d` of `printf` treats the argument for it as an `int`, which `1` apparently satisfies, and you see this output. Note that if the first field in `struct student` is not an `int`, the `printf` invokes undefined behavior. – yano Jun 03 '22 at 05:55
  • got it thank you. 1 is int data type btw. – user18025483 Jun 03 '22 at 06:08
  • furthermore, `&ST` is a pointer to an array of `struct student` objects 5 long. That is, a `struct student (*)[5]` type. Or if you were going to declare a variable, `struct student (*ptr2)[5] = &ST;`. If you print out the values for `ptr` and `ptr2` they'll be the same, since the first element of the array (where `ptr` points) is also the same as where the array begins (where `ptr2` points). But note the pointer arithmetic is different for these. `ptr+1` points to the 2nd element in the array. `ptr2+1` points to where the next 5-long object would start (there isn't one). – yano Jun 03 '22 at 06:21
  • see https://godbolt.org/z/Pb8cd4zMT – yano Jun 03 '22 at 06:21
  • 1
    Thank you that was interesting and helpful! – user18025483 Jun 03 '22 at 06:55

0 Answers0