在C中打印void *变量 [英] Printing a void* variable in C

查看:537
本文介绍了在C中打印void *变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我想用printf进行调试.但是我不知道如何打印输出"变量.

Hi all I want to do a debug with printf. But I don't know how to print the "out" variable.

在返回之前,我要打印此值,但是其类型为void *.

Before the return, I want to print this value, but its type is void* .

int 
hexstr2raw(char *in, void *out) {
    char c;
    uint32_t i = 0;
    uint8_t *b = (uint8_t*) out;
    while ((c = in[i]) != '\0') {
        uint8_t v;
        if (c >= '0' && c <= '9') {
            v = c - '0';
        } else if (c >= 'A' && c <= 'F') {
            v = 10 + c - 'A';
        } else if (c >= 'a' || c <= 'f') {
            v = 10 + c - 'a';
        } else {
            return -1;
        }
        if (i%2 == 0) {
            b[i/2] = (v << 4);
            printf("c='%c' \t v='%u' \t b[i/2]='%u' \t i='%u'\n", c,v ,b[i/2], i);}
        else {
            b[i/2] |= v;
            printf("c='%c' \t v='%u' \t b[i/2]='%u' \t i='%u'\n", c,v ,b[i/2], i);}
        i++;
    }
    printf("%s\n", out);
    return i;
}

我该怎么办?谢谢.

推荐答案

此:

uint8_t *b = (uint8_t*) out;

暗示out实际上是指向uint8_t的指针,因此也许您想打印实际存在的数据.另外请注意,您不需要从C中的void *进行强制转换,因此强制转换是毫无意义的.

implies that out is in fact a pointer to uint8_t, so perhaps you want to print the data that's actually there. Also note that you don't need to cast from void * in C, so the cast is really pointless.

代码似乎正在执行十六进制到二进制的转换,并将结果存储在out中.您可以执行以下操作来打印i生成的字节:

The code seems to be doing hex to binary conversion, storing the results at out. You can print the i generated bytes by doing:

int j;
for(j = 0; j < i; ++j)
  printf("%02x\n", ((uint8_t*) out)[j]);

指针值本身很少引起关注,但是您可以使用printf("%p\n", out);打印它. %p格式说明符用于void *.

The pointer value itself is rarely interesting, but you can print it with printf("%p\n", out);. The %p formatting specifier is for void *.

这篇关于在C中打印void *变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆