473,714 Members | 2,540 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

exercise problem -- not homework

I am going through the exercises and Bruce Eckel's Thinking in C++ and
I ran into an exercise that wasn't included in his solutions that I
think I could use some assistance with.

Exercise 3-26 pg 213:

Define an array of int. Take the starting address of that array and
use static_cast to convert it into an void*. Write a function that
takes a void*, a number (indicating a number of bytes), and a value
(indicating the value to which each byte should be set) as arguments.
The function should set each byte in the specified range to the
specified value. Try out the function on your array of int.

Here is what I have so far: (which isnt much)

#include <iostream>
using namespace std;

void fn (void* v, int n)
{
}
int main ()
{
int a[10];
void* vp = static_cast<voi d*>(&a);

return 0;
}

Maybe somebody can help me translate what is being asked in the
exercise.

Thanks in advance for any tips,
Charles
Jul 19 '05 #1
5 2531
<Charles> wrote in message
news:lm******** *************** *********@4ax.c om...
Did I correctly recast the void to the type you are describing?
The cast itself is correct, but it is of no use for you.
How do I set the value of each byte in the range as it applies to the
int array?
See below.
#include <iostream>
using namespace std;

void fn (void* v, size_t num_bytes, int value)
{
This is what Karl meant. You cannot really work with a void-pointer,
because it is an incomplete type. So you need to cast 'v' to something that
allows you to work on bytes.
for (size_t i = 0; i < num_bytes; ++i)
// set the bytes here How?
Once you have the above casting done, you can easily assign to the byte
array, just like you would do any other variable assignment.
}

int main ()
{
int a[10], number = 10;

void* p_v = static_cast<voi d*>(&a);
unsigned char* p_byte = reinterpret_cas t<unsigned char*>(p_v);
If you think about the use of this, what would it do? You cast to
'unsigned char', but what for?
fn (p_v, sizeof p_byte, number);
In the excerise it said your function takes a number "indicating a
number of bytes" .. you can assume that the number of bytes of the array you
are passing to the function are meant. But that is not what you are passing
there. You are passing the size of a pointer-to-unsigned-char, which is 4 on
my machine. But the size of your array that you are passing is 10 (not 10
bytes!), and each element occupies several bytes by itself. By this, you
should be able to figure out the actual size of the array in bytes.
return 0;
}


hth
--
jb

(replace y with x if you want to reply by e-mail)
Jul 19 '05 #2
On Mon, 28 Jul 2003 06:22:05 -0400, wrote:
Here the function should set the bytes indicated by the
starting address in void* to a value (which has not been
passed right now, but you are going to change this). There
are n bytes in sequence.
Hint: You can't do anything sensible with a void*, thus you
will need to cast the void* to some other pointer type. So
the question is: To what data type will you cast the void
pointer, such that the pointer can point to individual bytes

Hint2: sizeof( unsigned char) equals 1 per definition.
unsigned char is also often used, if somebody deals
with memory on the byte level.


You are asked to rewrite the standard function memset. Maybe
looking up its documentation may be of some help. Other then
that: The assignment seems to be pretty clearto me. Are there
any specific quesitions instead of the global: 'Help!'


Did I correctly recast the void to the type you are describing?

How do I set the value of each byte in the range as it applies to the
int array?

Charles
#include <iostream>
using namespace std;


#define ARRAY_SIZE 10
void fn (void* v, size_t num_bytes, int value)
void fn (void* v, size_t num_bytes, char value)

Since you'll be writing the value into each individual byto of the array
value should probably be of type char.
{
for (size_t i = 0; i < num_bytes; ++i)
// set the bytes here How?
Pointer arithmetic:

for(pointer = start ;pointer < start + size; pointer++) {
*pointer = value;
}
}

int main ()
{
int a[ARRAY_SIZE];
char number = 10;

void* p_v = static_cast<voi d*>(&a);
unsigned char* p_byte = reinterpret_cas t<unsigned char*>(p_v);

fn (p_v, sizeof p_byte, number);
fn (p_v, sizeof(int) * ARRAY_SIZE ,number)

return 0;
}

hth
npv
Jul 19 '05 #3
<Charles> wrote in message
news:uq******** *************** *********@4ax.c om...
Here is what I have in an attempt to apply the advice given to me in
this thread. It seems to satisfy the criteria given in the
exercise... Comments please?
#include <iostream>
using namespace std;

void fn (void* v, size_t num_bytes, int val)
{
unsigned char* p_addr =
reinterpret_cas t<unsigned char*>(v);
unsigned char byte =
static_cast<uns igned char>(val);

cout << "num_bytes = " << num_bytes << endl;

for (size_t i = 0; i < num_bytes; ++i)
{
*p_addr = byte;
p_addr++;
}
}

int main ()
{
int a[10], value = 67;

void* vp = static_cast<voi d*>(&a);

fn (vp, sizeof a, value);
The loop for printing the result seems wrong.
// output each of 4 bytes of int array
// index each element
for (size_t i = 0; i < (sizeof a / sizeof a[0]); ++i)
{
unsigned char* p_addr =
reinterpret_cas t<unsigned char*>(a[i]);
'a [i]' is of type 'int'. Above, you are casting that to 'unsigned
char*'. I think this is not what you intended to do. Instead, you probably
want to take the /address/ of the i-th element in the a-array, so that
p_addr points to the first byte that the i-th 'int' in the array occupies.
(*)
unsigned char byte =
static_cast<uns igned char>(a[i]);
I do not think this is intended either. 'byte' contains part of 'a [i]'.
Seeing the loop below, you print out 'byte', but you never change its value,
until the point of execution reaches the above line again. You can actually
remove this line completely.
// iterate each byte
for (size_t j = 0; j < sizeof(int); ++j)
{
cout << byte ;
p_addr++;
You seem to be thinking that incrementing 'p_addr' implicitly changes
'byte' as well. But this is not the case. The value you have assigned to
'byte' is just there, without any connection to where it came from.

If you did as I explained (the paragraph marked with an asterisk), then
you only need to change 'byte' in the above loop to '*p_addr' and it will
print out the real values. This works, because before the loop starts, you
let 'p_addr' point to the first byte of the element in the array (see
above). The inner loop then prints the bytes as you intended.
}
cout << endl;
}

return 0;
}

The output on my machine is:
num_bytes = 40
CCCC
CCCC
CCCC
CCCC
CCCC
CCCC
CCCC
CCCC
CCCC
CCCC


hth
--
jb

(replace y with x if you want to reply by e-mail)
Jul 19 '05 #4
The loop for printing the result seems wrong.

You are correct.
I noticed this too after I posted.

Here is my correction.
#include <iostream>
using namespace std;

void fn (void* v, size_t num_bytes, int val)
{
unsigned char* p_addr =
reinterpret_cas t<unsigned char*>(v);
unsigned char byte =
static_cast<uns igned char>(val);

cout << "num_bytes = " << num_bytes << endl;

for (size_t i = 0; i < num_bytes; ++i)
{
*p_addr = byte;
p_addr++;
}
}

int main ()
{
int a[10], value = 67;

void* vp = static_cast<voi d*>(&a);

fn (vp, sizeof a, value);

// output each of 4 bytes of int array
unsigned char* byte =
reinterpret_cas t<unsigned char*>(vp);

// iterate number of elements
for (size_t i = 0; i < (sizeof a / sizeof a[0]); ++i)
{
// iterate each byte per element
for (size_t j = 0; j < sizeof(int); ++j)
{
cout << *byte;
byte++;
}
cout << endl;
}

return 0;
}

Jul 19 '05 #5
This seems to be correct now for displaying the byte content of each
of the array elements.

If i change line 15

from
*p_addr = byte;

to
*p_addr = byte++;

I get the following output:

num_bytes = 40
CDEF
GHIJ
KLMN
OPQR
STUV
WXYZ
[\]^
_`ab
cdef
ghij

which, I think, shows that the program is setting and displaying 40
bytes for the 10 element int array.

Charles
Jul 19 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
3636
by: J Peterman | last post by:
I need to do this exercise, but am having problems. I need to write a program that firstly, sleeps for 5 seconds, then reads a line of input from file descriptor 0 and then writes the line back to file descriptor 1. Apparrantly, this program would block forever unless you type a line of text on the keyboard, but I can't get a working program to try. Next, this program needs to be modified so that it would write its input
18
1947
by: Andy Green | last post by:
Emphasis is on efficiancy and speed this is the excercise: The program should monitor a possibly infinite stream of characters from the keyboard (standard input). If it detects the sequence "aaa" it outputs a "0". If it detects the sequence "aba" it outputs a "1". DO NOT detect sequences within sequences. The program should exit cleanly when it detects an End Of Input. For example: The following sequence aababaaabaaa<End Of Input>...
12
2324
by: Merrill & Michele | last post by:
It's very difficult to do an exercise with elementary tools. It took me about fifteen minutes to get exercise 1-7: #include <stdio.h> int main(int orange, char **apple) { int c; c=-5; while(c != EOF ) {
3
4112
by: hossam | last post by:
I'm studying python newly and have an exercise that is difficult for me as a beginner.Here it is : "Write a program that approximates the value of pi by summing the terms of this series: 4/1-4/3+4/5-4/7+4/9-4/11+.... The program should prompt the user for n, the number of terms to sum and then output the sum of the first n terms of this series." any help would be appreciated.
6
9415
by: sathyashrayan | last post by:
Dear group, Following is a exercise from a book called "Oreilly's practical C programming". I just wanted to do a couple of C programming exercise. I do have K and R book, but let me try some simple one. Exercise 4-2: Write a program to print a block E using asterisks (*), where the E has a height of seven characters
10
2604
by: Eric | last post by:
Hello, I have been working through the K&R book (only chapter one so far) examples and exercises. After much sweat and hair pulling, I think I have a solution for ex 1-18 on page 31. It seems to work but may be missing some error checking. Can you please take a look and see if my logic is correct and any other improvements. This is not a homework but it could just as well be. I am trying to get a
5
2812
by: Richard Gromstein | last post by:
Hello, I have an exercise that I need to finish very soon and I really need help understanding what to do and how exactly to do it. I am working on reading the chapter right now and working on it myself, but I have a feeling I won't get far. Please help me complete the exercise. I am posting what needs to be done and will be updating with pieces of code that I come up with. Thank you all for your attention. ...
0
1156
by: Lambda | last post by:
It's from the Accelerated C++ exercise 8-1 The old version is based on pointer to function: double analysis(const std::vector<Student_info>& students, double analysis_grade(const Student_info& s)) { vector<doublegrades; transform(students.begin(), students.end(),
0
8704
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9307
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9071
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9009
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7946
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6627
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5943
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3155
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2105
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.