Home > Software design >  The result of printing an uint64_t array
The result of printing an uint64_t array

Time:01-12

I have this small piece of code:

uint64_t test[] = {1, 2, 3, 4, 5};
printf("test value: %llu\n", test);

I try to print the test array, and it gives me this number:

test value: 140732916721552

Can someone explain this and how an uint64_t array works? Thank you

CodePudding user response:

In your code

uint64_t test[] = {1, 2, 3, 4, 5};
printf("test value: %llu\n", test);

%llu tells printf that it shall print a long long unsigned integer. The test part of the printf statement pass a pointer to the first element of the array to printf. In other words, there is a mismatch between what you are passing (a pointer) and what you tell printf to print (long long unsigned).

In C such a mismatch leads to "undefined behavior". So in general it's not possible to say what will be printed. Any print out will be legal from a C standard point of view. No print out would also be legal. A program crash would be legal. Anything... would be legal.

It's impossible to say what goes on in general. On a specific system, it's possible to dig into the low level things and figure out what is going on. On my system the printed value corresponds to the address of the first array element interpreted as a long long unsigned integer. But don't rely on that. Other systems may do something completely different.

The code below shows how to correctly print the address of the array and the array elements.

#include <stdio.h>
#include <inttypes.h>

int main(void) 
{
    uint64_t test[] = {1, 2, 3, 4, 5};
    
    // Print the address where the array is located
    printf("Address of test value is %p\n", (void*)test);
    
    // Print the values of the array elements
    size_t sz = sizeof test / sizeof test[0];
    for (size_t i = 0; i < sz;   i)
      printf("test[%zu] is %" PRIu64 "\n", i, test[i]);
    
    return 0;
}

Output (note: address may differ in every invocation):

Address of test value is 0x7ffc4ace5730
test[0] is 1
test[1] is 2
test[2] is 3
test[3] is 4
test[4] is 5

CodePudding user response:

When you define an array like this in C, what you are actually doing is storing each of these values sequentially on the stack as separate uint64_ts. The value assigned to the test identifier is then a pointer to the first of these values, a uint64_t* rather than a uint64_t. When you print test, you are printing the pointer rather than any of the elements, i.e. the memory address of the first element in your array.

The [] notation is equivalent to

*(test   i)

i.e. it dereferences a pointer to the ith element.

  •  Tags:  
  • c
  • Related