-1

Trying to understand someone else's code. Two questions, it is redundant to cast pdata as uint8_t? And how to do I see the value of pdata?

void *pb; 
uint8_t *pdata  = NULL;

//re-cast pb as uint8_t type
pdata = (uint8_t*)pb; // now pdata is equal to a uint8_t of whatever pb is, pb is an empty pointer
pdata += 1000;
printf("%d\n", pdata[0]);
matt
  • 43
  • 6

2 Answers2

1

Two questions, it is redundant to cast pdata as uint8_t?

Yes? The only uint8_t* case in your code is from pd pointer with is a void* pointer. A void* pointer can be implicitly converted to pointer to another type. pdata is a pointer to uint8_t, so casting it as uint8_t* pointer would be redundant. Casting pdata as uint8_t like (uint8_t)pdata would yield an implementation defined value.

And how to do I see the value of pdata?

It's typical to cast a pointer to void* and then use %p printf format specifier to print the value of a pointer. Most environments I worked with just print the value of the pointer in hex then.

printf("%p\n", (void*)pdata);
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
0

Abstracting from the case when the author of the code does not know what he/she is doing such a cast (which in C is redundant) can be seen in:

  1. The MISRA or another industrial standards compliant code (otherwise code analysers will cry)
  2. Code which is likely to be compiled by the C++ compiler (yes I know it should not happen, but in real life someone can take your code and complain ...)
0___________
  • 60,014
  • 4
  • 34
  • 74