0

I am studying for exam and I came across this statement. I have read couple of books and notes and so far i have not come across this and also i dont even know what to call it so i have not able to find the answer.

Here it goes.

 typedef struct {
         unsigned a: 4;
         unsigned b: 4;
 } byte, *pByte;// what does *pbyte means here?

int main(){
pByte p = (pByte)x; // this is typecasting void pointer. how does it work with *pbyte
 byte temp;
 unsigned i;

 for(i = 0u; i < n; i++) {
         temp = p[i]; //again I have no idea why we suddenly have array
 }
}

Again if i dont know something basic......well I dont know cause im still learning :) help me out please. thanks.

LihO
  • 41,190
  • 11
  • 99
  • 167
Soban Khan
  • 19
  • 6
  • You seriously should [read this question from beginning to end](http://stackoverflow.com/questions/5727/what-are-the-barriers-to-understanding-pointers-and-what-can-be-done-to-overcome), particularly the first answer, which is simply amazing. – WhozCraig Oct 24 '13 at 19:39
  • I've also added [tag:c] tag since AFAIK this very concrete "problem" is same for both languages. – LihO Oct 24 '13 at 19:54

1 Answers1

1
typedef struct {
    ...
} byte, *pByte;

defines a structure with an alias byte and defines an alias pByte for byte* as well, so that you can use it the following way:

byte b;
pByte pB = &b;

which is also equivalent to:

byte b;
byte* pB = &b;

So in case you have a void pointer x (which is a bit suspicious and if it is possible you should try to avoid using void* at first place) and you know it points to the first element of an array of n structs:

pByte p = (pByte) x;          // casts x back to the correct type
byte temp;

then

temp = p[i];

is possible and equivalent to (pointer arithmetic) :

temp = *(p + i);
LihO
  • 41,190
  • 11
  • 99
  • 167
  • 2
    +1 short and direct. nice explanation. It should be noted that most professional C programmers do *not* like pointer-typedefs, as they tend to mask the in-your-face attention the asterisks bring to the reviewer. `Type *p;` declares a pointer, and its obvious. `TypeP p;` ? Um... They do, however, have one particular quality. `byte* pB, pC;` does not declare two pointers, whereas `pByte pB, pC;` *does*. This isn't a substantial gain, however, since the former won't even compile if you try to use `pC` like a pointer. I.e. you'll catch that mistake at compile time (usually). – WhozCraig Oct 24 '13 at 19:45
  • @WhozCraig: As long as the alias somehow carries the information that it is an alias for a pointer (i.e. `pByte`, `BytePtr`, etc.) I guess it's still fine. Otherwise it's a nasty stuff indeed. – LihO Oct 24 '13 at 19:57
  • @KeithThompson: It surely does. I'm just saying that once someone decides to make an alias for a pointer, he should explicitly express this fact in its name at least. – LihO Oct 25 '13 at 01:17