C打印一个void *缓冲区

时间:2011-10-20 08:13:09

标签: c printf void-pointers

kay所以这个

void printPacketBuffer(void *buffer, unsigned int length)
{
    unsigned int i=0;
    char *c;
    unsigned int limit = ( (length != 0)?length:PACKET_DATA );
    for (i=0; i<limit; i++) {
        c = (char *)(buffer+i);
        if ( *c != '\0' ) {
            printf("%c", *c);
        }
    }
}

正在工作但是以下函数短缺了最后14个字节无法理解为什么?

void printPacket (void * buffer) {
    unsigned int size = getPacket_size(buffer);
    printf("\n***********\nNew Packet holding %d bytes of data\n***********\n", size);
    char *c;
    int counter=0;
    int i;
    for (i=2; i<size+2; i++) {
        c = (char *)(buffer+i);
        if ( *c != '\0' ) {
            printf("%c", *c);
            counter++;
        }
    }
    printf("\nactual printing %d, i=%d\n", counter, i);
}

这是电话

printPacketBuffer(pbuffer+2, getPacket_size(pbuffer));
printPacket(pbuffer);

1 个答案:

答案 0 :(得分:0)

我认为pbuffer + 2是两个字节的下一个地址但我错了这里发生的事情 如果bpuffer = 0x7fff2c03d8a0 bpuffer + 2 = 0x7fff2c03d8b0 现在转移到我使用的下一个2字节位置

void *temp = (char *)pbuffer+shift;

无论如何,故事的士气是使用转换为unsigned char

的字节
void printPacket (void * buffer) {
    unsigned int size = getPacket_size(buffer);
    printf("\n***********\nNew Packet holding %d bytes of data %p\n***********\n", size, buffer);
    char *c;
    int counter=0;
    int i;
    for (i=2; i<size+2; i++) {
        c = (char *)buffer+i;
        if ( *c != '\0' ) {
            printf("%c", *c);
            counter++;
        }
        else {
            printf("NULL ");
        }
    }
}