🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

1 total messages Started by Pawel Mrozik Mon, 25 Sep 2000 00:00
Casts
#47
Author: Pawel Mrozik
Date: Mon, 25 Sep 2000 00:00
66 lines
2980 bytes
I downloaded Eckel's "Thinking in C++" book in PDF format, and I've been
trying to get through the exercises. I'm currently stuck on one of the
problems. I'm pasting everything below:

// Thinking in C++
// Chapter 3 - Exercise 28
// Filename: ch3ex28.cpp
// Assignment: 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_cast 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?

----------------------------------------------------------------------------
------
#include <iostream>
using namespace std;
void printElement(double *ptr, int ptrsize);

void main()
{

 double k[5] = {0, 0, 0, 0, 0};
 printElement(k, sizeof(k)/8);
 unsigned char *startAdd = reinterpret_cast<unsigned char*>(&k);

    for(int i = 0; i < 5; i++)
     {
      startAdd[i] = 1;
     }
     for(i = 0; i < 5; i++)
          cout << startAdd[i] << endl;

}

void printElement(double *ptr, int ptrsize)
{

 for(int i = 0; i < ptrsize; i++)
  cout << ptr[i] << endl;

}
----------------------------------------------------------------------------
------

1) Did I write printElement correctly? Is there another way to tell a
function what the size of the array is?
2) The second for loop in main() prints out null characters. I'm assuming
that the reason that the integer 1 cannot be assigned to *startAdd because
of the differences between unsigned char and double, which not only take up
a different amount of space in memory, but are also of different types. Am I
missing something?
3) Eckel often declares his main() function as an int, but never has a
'return 0;' in any of his programs. My compiler (VC++) spits out an error
when the function doesn't return a value. Is there something wrong with
Eckel's code or my compiler?

Thanks in advance.

-Pawel Mrozik
Thread Navigation

This is a paginated view of messages in the thread with full content displayed inline.

Messages are displayed in chronological order, with the original post highlighted in green.

Use pagination controls to navigate through all messages in large threads.

Back to All Threads