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?
Please help :).
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;
}
}
Comment