How to print the contents of a unsigned char array within a struct?

Viewed 898

I have the following struct that contains an unsigned char array and I don't know how to print the contents of the array within the struct in the following context.

The char array is null terminated.

typedef data_type
{
  int a;
  unsigned char b;
  unsigned char c[33];
} DATA_TYPE, *DATA;

I create an instance of the struct

DATA data;
data = (DATA) malloc(sizeof(DATA_TYPE);

/* some code where I populate its values... */

printf("data->a = %d", data->a);
printf("data->b = %u", data->b);
printf("data->c = NOT SURE HOW TO PRINT THIS PART");
3 Answers

In addition to @Fiddling Bits good answer:

If data->c lacks a null character, all the array can be printed as text with a precision. It limits output to (int) sizeof data->c, the size of the array. Note the precision is an int argument and sizeof returns a size_t, hence the cast below.

printf("%.*s\n", (int) sizeof data->c, data->c);

With a null character in data->c, the above acts like "%s".

If it's a NUL ('\0') terminated string, you can use what was suggested in the comments (printf("data->c = %s", data->c);). If not, you can use a loop to print the entire array. For example:

printf("data->c = ");
for(i = 0; i < sizeof(data->c); i++)
    printf("%u ", data->c[i]);
printf("\n");

Does c contain a NUL terminated C string? If so, use %s.

Otherwise, you need to write your own display function iterating over the c array in some way.

Personally, I would reuse one of the dozen or so implementations of a void hexdump(const void *buf, const size_t size) or similar function I have written over the last twenty years.

Some C standard libraries also allow hooking your own format character into the *printf function, but that probably is not very portable.

Related