代码之家  ›  专栏  ›  技术社区  ›  sdbbs

为什么带%p指针格式说明符的printf会在AVR上打印垃圾字符而不是地址?

avr c
  •  0
  • sdbbs  · 技术社区  · 6 年前

    我见过 How to find the address of a variable when using AVR? -结论是:

    ... 但我真的搞不懂为什么我的问题会发生。

    我有一个变量,我想用作“字符串数组”,我想malloc和realloc:

    char** my_array = malloc(sizeof(char*)*1);
    

    printf 重定向到“打印”到USB串行端口,然后我在串行终端读取打印输出。

    %p printf的格式说明符应将变量的地址打印为十六进制数。我有这样一个声明:

    printf("my_array %p\r\n", (void *)&my_array);
    

    我也试过:

    printf("my_array %p\r\n", &my_array);
    printf("my_array %p\r\n", my_array);
    

    my_array  ▒▒▒ꓣ▒▒▒▒/▒▒f'w'▒`$▒▒W*▒▒X▒f'w'▒`$▒▒Y*▒▒Z▒f'w'▒`▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒#▒▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒j▒{▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒i▒z▒▒`$▒▒
    

    ... 这显然不是十六进制数。

    为什么会这样,我做错了什么?我怎样才能在AVR中得到一个十六进制变量的地址呢?如果重要的话,我使用CodeVisionAVR编译器。。。


    https://www.avrfreaks.net/forum/format-specifier-pointers-0

    但是人们是否真的使用了%p,尤其是在AVR上。在AVR上,指针是一个16位无符号数。我一般都会自己用%04X或者别的什么。

    (好的,刚刚意识到这个论坛可能意味着32位ARM或UC3,我猜指针是32位的?即使如此(在这种情况下为%08X)

    printf("my_array %08X\r\n", (void *)&my_array);
    

    ... 现在我得到打印输出:

    my_array 00003FFB
    

    ... 但现在我不知道这是不是一个真实的地址 :)

    1 回复  |  直到 6 年前
        1
  •  1
  •   dbush    6 年前

    您可以将指针投射到 uintptr_t

    printf("my_array %llu\r\n", (unsigned long long)(uintptr_t)&my_array);