exercise on reinterpret_cast
Hi,
I am trying the following exercise in a book:
//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.
#include <iostream>
void func(void* p,short int s,unsigned char v)
{
unsigned char * pp=reinterpret_cast<unsigned char*>(p);
for (int i=0;i<s;i++)
{
*(pp+i)=v;
}
}
int main()
{
unsigned int iA[10];
for (int i=0;i<10;i++)
{
int j;
std::cout << "gimme some int" << std::endl;
std::cin >> j;
iA[i]=j;
}
for (int i=0;i<10;i++)
{
std::cout << iA[i] << std::endl;
}
void * p=static_cast<void *>(&iA);
std::cout << "gimme a number of bytes to change" << std::endl;
short i;
std::cin >> i;
std::cout << "gimme a value I will force those bytes to" << std::endl;
char j;
std::cin >> j;
func(p,i,j);
for (int i=0;i<10;i++)
{
std::cout << iA[i] << std::endl;
}
}
I am then expecting that, if I set my whoke array to zero, and I suggest to
change just one byte to 255, I'll have iA[0]=255 and all the other worth 0
(my int are 4 bytes long so when I change 1 byte I just change part of the
first int and shouldn't touch the rest).
But I get 50 for the first element instead.
Can you please tell me where I am wrong?
Thank you