简体   繁体   中英

C++ static_cast from int* to void* to char* - can you help me to understand this code?

I'm a beginner in C++, and I have problem with understanding some code.

I had an exercise to do, to write function which returns size of int , and do not use sizeof() and reinterpret_cast . Someone gave me solution, but I do not understand how it works. Can you please help me to understand it? This is the code:

int intSize() {
  int intArray[10];
  int * intPtr1;
  int * intPtr2;

  intPtr1 = &intArray[1];
  intPtr2 = &intArray[2];

  //Why cast int pointer to void pointer?
  void* voidPtr1 = static_cast<void*>(intPtr1);

  //why cast void pointer to char pointer?
  char* charPtr1 = static_cast<char*>(voidPtr1);

  void* voidPtr2 = static_cast<void*>(intPtr2);
  char* charPtr2 = static_cast<char*>(voidPtr2);

  //when I try to print 'charPtr1' there is nothing printed
  //when try to print charPtr2 - charPtr1, there is correct value shown - 4, why?
  return charPtr2 - charPtr1;
}

To summarize what I don't understand is, why we have to change int* to void* and then to char* to do this task? And why we have the result when we subtract charPtr2 and charPtr1 , but there is nothing shown when try to print only charPtr1 ?

First of all, never do this in real-world code. You will blow off your leg, look like an idiot and all the cool kids will laugh at you.

That being said, here's how it works: The basic idea is that the size of an int is equal to the offset between two elements in an int array in bytes. Ints in an array are tightly packed, so the beginning of the second int comes right after the end of the first one:

int* intPtr1 = &intArray[0];
int* intPtr2 = &intArray[1];

The problem here is that when subtracting two int pointers, you won't get the difference in bytes, but the difference in ints. So intPtr2 - intPtr1 is 1 , because they are 1 int apart.

But we are in C++, so we can cast pointers to anything! So instead of using int pointers, we copy the value to char pointers, which are 1 byte in size (at least on most platforms).

char* charPtr1 = reinterpret_cast<char*>(intPtr1);
char* charPtr2 = reinterpret_cast<char*>(intPtr2);

The difference charPtr2 - charPtr1 is the size in bytes. The pointers still point to the same location as before (ie the start of the second and first int in the array), but the difference will now be calculated in sizes of char , not in sizes of int .

Since the exercise did not allow reinterpret_cast you will have to resort to another trick. You cannot static_cast from int* to char* directly. This is C++'s way of protecting you from doing something stupid. The trick is to cast to void* first. You can static_cast any pointer type to void* and from void* to any pointer type.

This is the important bit:

intPtr1 = &intArray[1];
intPtr2 = &intArray[2];

This creates two pointers to adjacent ints in the array. The distance between these two pointers is the size of an integer that you're trying to retrieve. However the way that pointer arithmetic works is that if you subtract these two then the compiler will return you the size in terms of ints, which will always be 1.

So what you're doing next is re-casting these as character pointers. Characters are (or de-facto are) 1 byte each, so the difference between these two pointers as character pointers will give you an answer in bytes. That's why you're casting to character pointers and subtracting.

As for via void* - this is to avoid having to use reinterpret_cast . You're not allowed to cast directly from a int* to a char* with static_cast<> , but going via void* removes this restriction since the compiler no longer knows it started with an int* . You could also just use a C-style cast instead, (char*)(intPtr1) .

"do not use sizeof() and reinterpret_cast"... nothing's said about std::numeric_limits, so you could do it like that :)

#include <limits>

int intSize()
{
   // digits returns non-sign bits, so add 1 and divide by 8 (bits in a byte)
   return (std::numeric_limits<int>::digits+1)/8;
}

Please read this: richly commented.

int intSize()
{
    int intArray[2]; // Allocate two elements. We don't need any more than that.

    /*intPtr1 and intPtr2 point to the addresses of the zeroth and first array elements*/
    int* intPtr1 = &intArray[0]; // Arrays in C++ are zero based
    int* intPtr2 = &intArray[1];

    /*Note that intPtr2 - intPtr1 measures the distance in memory 
      between the array elements in units of int*/

    /*What we want to do is measure that distance in units of char;
      i.e. in bytes since once char is one byte*/

    /*The trick is to cast from int* to char*. In c++ you need to 
      do this via void* if you are not allowed to use reinterpret_cast*/

     void* voidPtr1 = static_cast<void*>(intPtr1);
     char* charPtr1 = static_cast<char*>(voidPtr1);

     void* voidPtr2 = static_cast<void*>(intPtr2);
     char* charPtr2 = static_cast<char*>(voidPtr2);

    /*The distance in memory will now be measure in units of char; 
      that's how pointer arithmetic works*/
    /*Since the original array is a contiguous memory block, the 
      distance will be the size of each element, i.e. sizeof(int) */
     return charPtr2 - charPtr1;
}

Pointer subtraction in C++ gives the number of elements between the pointed to objects. In other words, intPtr2 - intPtr1 would return the number of int between these two pointers. The program wants to know the number of bytes ( char ), so it converts the int* to char* . Apparently, the author doesn't want to use reinterpret_cast either. And static_cast will not allow a direct convertion from int* to char* , so he goes through void* (which is allowed).

Having said all that: judging from the name of the function and how the pointers are actually initialized, a much simpler implementation of this would be:

int
intSize()
{
    return sizeof( int );
}

There is actually no need to convert to void* , other than avoiding reinterpret_cast .

Converting from a pointer-to- int to a pointer-to- char can be done in one step with a reinterpret_cast , or a C-style cast (which, by the standard, ends up doing a reinterpret_cast ). You could do a C-style cast directly, but as that (by the standard) is a reinterpret_cast in that context, you'd violate the requirements. Very tricky!

However, you can convert from an int* to a char* through the void* intermediary using only static_cast . This is a small hole in the C++ type system -- you are doing a two-step reinterpret_cast without ever calling it -- because void* conversion is given special permission to be done via static_cast .

So all of the void* stuff is just to avoid the reinterpret_cast requirement, and would be silly to do in real code -- being aware you can do it might help understanding when someone did it accidentally in code (ie, your int* appears to be pointing at a string: how did that happen? Well, someone must have gone through a hole in the type system. Either a C-style cast (and hence a reinterpret_cast ), or it must have round-tripped through void* via static_cast ).

If we ignore that gymnastics, we now have an array of int . We take pointers to adjacent elements. In C++, arrays are packed, with the difference between adjacent elements equal to the sizeof the elements.

We then convert those pointers to pointers-to- char , because we know (by the standard) that sizeof(char)==1 . We subtract these char pointers, as that tells us how many multiples-of- sizeof(char) there are between them (if we subtract int pointers, we get how many multiples-of- sizeof(int) there are between them), which ends up being the size of the int .

If we try to print charPtr1 through std::cout , std::cout assumes that our char* is a pointer-to- \\0 -terminated-buffer-of- char , due to C/C++ convention. The first char pointed to is \\0 , so std::cout prints nothing. If we wanted to print the pointer value of the char* , we'd have to cast it to something like void* (maybe via static_cast<void*>(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