Arrays + reinterpret_cast Help

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • JavierL
    New Member
    • Apr 2010
    • 17

    Arrays + reinterpret_cast Help

    I am doing a practice exercise from "thinking in c++" whose answer isn't covered in the annotated solutions guide, so I'm trying to handle it, but I don't understand what I'm doing wrong. Here is the exercise:

    28.Create a function that takes a pointer to an array of double and a value indicating the size of that array. The function should print each element in the array. Now create an array of double and initialize each element to zero, then use your function to print the array. Next use reinterpret_cas t to cast the starting address of your array to an unsigned char*, and set each byte of the array to 1 (hint: you’ll need to use sizeof to calculate the number of bytes in a double). Now use your array-printing function to print the results. Why do you think each element was not set to the value 1.0?

    Code:
    using namespace std;
    
        int main()
        {
            double p[6]={0,0,0,0,0,0};
            array_passer(p,6);
            return 0;
        }
    
    void array_passer(double *p, int size){
    
    
        unsigned char* x = reinterpret_cast<unsigned char*>(&p);
            for(int i = 0; i < sizeof(double)*size; i++){
                *(x+i) = 1;  // With the debugger i get an issue over here but it prints some '1' on the bytes
              //  cout << x[i]<<endl;
            }
        double *z= reinterpret_cast<double*>(&x);
        for(int i =0;i<size;i++){
            cout << z[i] << endl;
        }
    }
    Please help :).
  • whodgson
    Contributor
    • Jan 2007
    • 542

    #2
    Once is enough. e.g. array[6]={0};
    to what does size refer and where is it initialized?

    Comment

    • JavierL
      New Member
      • Apr 2010
      • 17

      #3
      Is the array size it is passed through the function array_passer.

      Comment

      • newb16
        Contributor
        • Jul 2008
        • 687

        #4
        >unsigned char* x = reinterpret_cas t<unsigned char*>(&p);

        Wrong - you need to reinterpret p, pointer value p contains, not the address of pointer variable itself.
        unsigned char* x = reinterpret_cas t<unsigned char*>(p);

        > double *z= reinterpret_cas t<double*>(&x) ;
        Again - here you takes an address of you local variable x, not the value it contains.
        Should be double *z= reinterpret_cas t<double*>(x);

        Comment

        • Frinavale
          Recognized Expert Expert
          • Oct 2006
          • 9749

          #5
          I learned something new today :)
          For those of us who don't know what reinterpret_cas t does (or how to use it) here's the MSDN documentation on the reinterpret_cas t Operator (C++).

          -Frinny

          Comment

          Working...