3

If I have :

char *name; //this is in a struct

*row->name //row is able to get in the struct

How do I read *row->name and what is it returning?

I'll link the code I am reading: http://pastebin.com/MvLXkDCz

bolov
  • 72,283
  • 15
  • 145
  • 224
don
  • 41
  • 2
  • It's returning the first element `name` points to. It's like `row->name[0]` which should be used instead to avoid "*confusion*". – Iharob Al Asimi May 18 '16 at 16:46
  • 2
    Learn about [*operator precedence*](http://en.cppreference.com/w/c/language/operator_precedence). – Some programmer dude May 18 '16 at 16:47
  • @iharob if name is not initialized then what would get passed to sizeof(*row->name)? – don May 18 '16 at 16:52
  • 1
    @don sizeof is calculated at compile time using only type information. – Matt May 18 '16 at 16:53
  • @don As others said, [`sizeof` does not "*evaluate*" it's operand](http://stackoverflow.com/questions/8225776/why-does-sizeofx-not-increment-x) so nothing bad would happen, and it's actually a good way of passing the size to `malloc()` for example, for many reasons. For example, if you change the type of `name` you don't need to change *every* `malloc()` and also because it helps you allocate the correct size since it's always correct. – Iharob Al Asimi May 18 '16 at 17:00
  • @don `so 1 byte?` size_t (i.e. unsigned int) to be exact. – Matt May 18 '16 at 17:02
  • Questions are required to contain all relevant information **in the question itself**! Not a a link, nor as an image. – too honest for this site May 18 '16 at 18:31

2 Answers2

3

First the -> operator is evaluated and then the resulting pointer which is pointing to what name points to is dereferenced with *. So it's the same as

row->name[0]

and IMHO this is a better way of expressing the same (althought sometimes using the indirection operator * is clearer).

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
0

The -> component selection operator has higher precedence than the unary * operator, so *row->name is parsed as *(row->name); you're dereferencing the row->name member.

The same is true for all other postfix1 operators:

*arr[i] == *(arr[i])
*foo()  == *(foo())
*a.p    == *(a.p)
*p++    == *(p++)
*q--    == *(q--)


  1. Component selection operators `.` and `->` are grouped with postfix operators even though they look like infix operators.

John Bode
  • 119,563
  • 19
  • 122
  • 198