简体   繁体   English

如何取消引用strlen内部的void指针?

[英]How to dereference a void pointer inside strlen?

I wrote a signedness agnostic function to print char string in hexadecimal format. 我编写了一个不可知函数,以十六进制格式打印char字符串。

void print_char2hex(void* cp) {

    const char *arr = (char *) cp;

    size_t i;

    for(i = 0; i < strlen( arr ); i++) {
        printf("%02X ", 0xFF & arr[i]);
    }
}

Why does the following code not compile? 为什么以下代码无法编译?

void print_char2hex(const void *cp) {

    size_t i;

    for (i = 0; i < strlen( * (const char *) cp ); i++) {
        printf("%02X ", 0xFF & cp[i]);
    }
}

This is the error message: 这是错误消息:

passing argument 1 of strlen makes pointer from integer without a cast [-Wint-conversion]

strlen expects a char* . strlen需要一个char* You're passing a char . 您正在传递一个char Change to: strlen( (const char *) cp ) by removing the dereferencing. 通过删除取消引用更改为: strlen( (const char *) cp )

There's also a problem in the printf statement. printf语句中还有一个问题。 You need to cast cp there too. 您也需要在此处cp Change to: printf("%02X ",0xFF & ((const char*)cp)[i]); 更改为: printf("%02X ",0xFF & ((const char*)cp)[i]);

Another remark is that it can affect performance to do the function call to strlen in the loop header. 另一点是,在循环头中执行strlen函数调用会影响性能。 Maybe the optimizer can fix it, but to be sure it can be better to use an extra line for that. 也许优化器可以修复它,但是要确保最好使用额外的一行。

size_t len = strlen( (const char *) cp );
for(i = 0; i < len ; i++) {

If you ask me, it also looks clearer. 如果您问我,它也看起来更清晰。

How to dereference a void pointer inside strlen? 如何取消引用strlen内部的void指针?

Inside strlen(const char *) , a de-reference is not needed. strlen(const char *) ,不需要取消引用。 Simply pass cp . 只需传递cp

void print_char2hex(const void *cp) {
  size_t len = strlen(cp);
  ...

Yet strlen() not needed. 但是不需要strlen()

void print_char2hex(const void *cp) {
  const unsigned char *p = cp;
  while (*p) {
    printf("%02X ", *p++);
  }
}

0xFF & is unnecessary, the shorter solution is: 0xFF &是不必要的,较短的解决方案是:

void print_char2hex(const void *cp) {
  const unsigned char *p = cp;
  while (*p != '\0') {
    printf("%02X ", (const unsigned char) *p++);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM