Home > Software engineering >  how to print contents of a void *?
how to print contents of a void *?

Time:01-15

static inline uint256_t sha256(const void *data, size_t len)
{
    secp256k1_sha256_t cxt;
    secp256k1_sha256_initialize(&cxt);
    secp256k1_sha256_write(&cxt, (uint8_t *)data, (int)len);
    uint256_t res;
    secp256k1_sha256_finalize(&cxt, (uint8_t *)&res);
    return res;
} 

I want to see what's inside data and what's being returned by the above function, so printing seems like an easy way but how do i print contents of *data not the pointer to data because *%p* gave me an address.

CodePudding user response:

  1. If you want to print the pointer address:
printf("%p", data);
  1. If you want to print the value (data), then you need to cast the pointer to something else, probably a (const char *). Used a "%s" which would work well if data is string:
printf("%*s", (int) len, (const char *) data);

If your data is binary or contain '\0' bytes then you probably hex encoding instead.

CodePudding user response:

Use a loop.

const unsigned char *bytes = data;
for (size_t i = 0; i < len; i  ) {
  printf("X ", bytes[i]);
}
  • Related