简体   繁体   中英

How to dereference a void pointer inside strlen?

I wrote a signedness agnostic function to print char string in hexadecimal format.

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* . You're passing a char . Change to: strlen( (const char *) cp ) by removing the dereferencing.

There's also a problem in the printf statement. You need to cast cp there too. Change to: 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. 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?

Inside strlen(const char *) , a de-reference is not needed. Simply pass cp .

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

Yet strlen() not needed.

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

0xFF & is unnecessary, the shorter solution is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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