Home > Software engineering >  Output from printing the contents of an int array by using a char*
Output from printing the contents of an int array by using a char*

Time:12-01

Do you know why the output of the program below is

1000
2000

I am very grateful if you can help me! Here is the program.

int main()
{
    int t[] = { 1, 2 };
    char* p = (char*)t;
    int i;
    for (i = 0; i < sizeof(t); i  )
    {
        printf("%d", *(p   i));

        if (i % sizeof(t[0]) == sizeof(t[0]) - 1) printf("\n");
    }
    return 0;
}

CodePudding user response:

It is printing the value of each byte in the value of t as a numerical value. The if statement at the end looks confusing, but just checks if it is at the final element then adds a line break before exiting. Here is the code rewritten in a more readable form.

int main() {
    int t[] = { 1, 2 };

    // Get a pointer to he first byte in t
    char* p = (char*)t;

    // Go through each byte in t
    for (int i = 0; i < sizeof(t); i  ) {
        // Print the numerical value of each byte
        printf("%d", p[i]);
    }

    // Add a line break when finished.
    printf("\n");

    return 0;
}

The objective of this code is most likely to show if you are using big or little endian. From your output we can tell you are using little endian. If it was big endian it would have outputted 00010002.

CodePudding user response:

You can clarify it a bit by changing the printf to printf("%d ", p[i]);.

What the code does is to iterate across an array of int byte by byte. A special rule in C allows us to inspect the raw data of pretty much any type, by using a pointer to character type and then access individual bytes.

char is however a very poor choice because of Is char signed or unsigned by default?. Use unsigned char or uint8_t instead.

As for why the raw byte presentation of an int with value 1 comes up as 1 0 0 0, it's because your systems happens to be a 32 bit int little endian system. What is CPU endianness?

The if (i % sizeof(t[0]) == sizeof(t[0]) - 1) printf("\n"); part is just to print the new line after 4 bytes.

A complete rewrite of the program might look like this:

#include <stdio.h>

int main (void)
{
  int t[] = { 1, 2 };
  const size_t t_items = sizeof(t)/sizeof(*t); // 8/4 = 2 items
  unsigned char* p = (unsigned char*)t; // bug fix to make the code portable

  for (size_t i = 0; i<t_items; i  ) // iterate across array items
  {
    for(size_t j=0; j<sizeof(int); j  ) // iterate across the bytes of each int
    {
      printf("%d ", *p);
      p  ;
    }
    printf("\n");
  }
}
  • Related