簡體   English   中英

打印 uint64_t 數組的結果

[英]The result of printing an uint64_t array

我有這么一小段代碼:

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

我嘗試打印test數組,它給了我這個數字:

test value: 140732916721552

有人可以解釋一下 uint64_t 數組的工作原理嗎? 謝謝

在你的代碼中

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

%llu告訴printf它應該打印一個long long unsigned printf語句的test部分將指向數組第一個元素的指針傳遞給printf 換句話說,您傳遞的內容(指針)與您告訴printf打印的內容(long long unsigned)不匹配。

在 C 中,這種不匹配會導致“未定義的行為”。 所以一般來說,不可能說會打印什么。 從 C 標准的角度來看,任何打印輸出都是合法的。 不打印出來也是合法的。 程序崩潰是合法的。 任何……都是合法的。

不可能說一般情況下會發生什么。 在特定系統上,可以深入研究底層事物並弄清楚發生了什么。 在我的系統上,打印值對應於第一個數組元素的地址,該元素被解釋為 long long unsigned integer。但不要依賴它。 其他系統可能會做一些完全不同的事情。

下面的代碼顯示了如何正確打印數組的地址和數組元素。

#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(注意:每次調用的地址可能不同):

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

當您在 C 中定義這樣的數組時,您實際做的是將這些值中的每一個作為單獨的uint64_t按順序存儲在堆棧上。 分配給test標識符的值是指向這些值中第一個的指針,一個uint64_t*而不是uint64_t 當您打印test時,您打印的是指針而不是任何元素,即數組中第一個元素的 memory 地址。

[]表示法等同於

*(test + i)

即它取消引用指向第i個元素的指針。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM