Void reinterpret cast question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jfsd
    New Member
    • Aug 2008
    • 2

    #1

    Void reinterpret cast question

    Hello, I have got a question, in the following code:

    Code:
    void func(void* v, int n, int val) {
        int* xp = reinterpret_cast<int*>(&v);
        for(int* i=xp; i<xp+n; i++)
           *i = 5;
    }
    int main() {
        int array[10];
        func(array, 10, 5);
    
        for (int j=0; j<10; j++)
            cout << array[j] << endl;
    }
    When passing the array into the function the array values don't change. However, if I just put the function contents directly in main(), I manage to change the values of the array.
    Am I doing something wrong?
  • newb16
    Contributor
    • Jul 2008
    • 687

    #2
    because this is not original pointer to the beginning of array, but pointer to
    v pointer itself ( &v ).
    int* xp = reinterpret_cas t<int*>(&v);

    Comment

    • jfsd
      New Member
      • Aug 2008
      • 2

      #3
      Thanks for the hint. Changing the line to this makes it work:
      Code:
      int* xp = reinterpret_cast<int*>(v);

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        reinterpret_cas t is not required.

        What is required is understanding how arrays work.

        Read this: http://bytes.com/forum/thread772412.html.

        I have never seen a case in C++ where you need write a new function with a void* argument.

        Comment

        • Billiska
          New Member
          • Aug 2008
          • 13

          #5
          First, I agree with the above reply that we rarely need to use void pointer as an argument.
          However, I still think there are some circumstances that we need it.

          Anyway, for this case, why don't you change it to
          Code:
          void func(int* v, int n, int val) {
          or
          Code:
          void func(int v[], int n, int val) {
          instead, so that you don't have to worry about changing the type.

          Another alternative way would be to use "memset" function.
          You can find a documentation here

          And if you want to use this function for many types of data, I suggest you define it using "template " like this:
          Code:
          template <class T>
          void func(T* v, T n, T val) {
              T* xp = v;
              for(T* i=xp; i<xp+n; i++)
                 *i = val;
          }
          *I think you want to put "val" there instead of "5", so I changed it.

          Comment

          Working...