首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

Thinking in C++的一道课后题,该怎么解决

2012-03-20 
Thinking in C++的一道课后题定义一个int数组。获得该数组的起始地址,使用static_cast把它转化为void*。写一

Thinking in C++的一道课后题
定义一个int数组。获得该数组的起始地址,使用static_cast把它转化为void*。写一个带以下参数的函数:一个void*,一个数字(表明字节的数目)和一个值(表明每个字节需要设定的值)。该函数必须为特定范围内的每个字节设定特定的值。在这个int数组上试验函数。

请带上注释。谢谢。

[解决办法]

C/C++ code
#include <iostream>using namespace std;int SetArray(void*, const int, const int);int main(){    int nArray[] = {0,1,2,3,4,5,6,7,8,9};    void *p = static_cast<void*>(nArray);    SetArray(p,4,5);    for (int i = 0; i < 10; i++)    {        cout<<nArray[i]<<endl;    }    system("pause");}int SetArray(void* pA, const int size, const int value){    int *t = static_cast<int*>(pA);    for (int i = 0; i < size; i++)    {        t[i] = value;    }    return 1;}
[解决办法]
楼上的有点小错误。我这个是手写,不保证正确。

C/C++ code
#include <iostream>// 写一个带以下参数的函数:一个void*,一个数字(表明字节的数目)和一个值(表明每个字节需要设定的值)。void SetArray(void* p, const int size, const int value){    if (0 != p)    {        unsigned char* pA = static_cast<unsigned char*>(p);        for (int i = 0; i < size; ++i)        {            // 该函数必须为特定范围内的每个字节设定特定的值。            pA[i] = static_cast<unsigned char>(value);        }    }}int main(){    int nArray[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};    // 获得该数组的起始地址,使用static_cast把它转化为void*。    void *p = static_cast<void*>(nArray);    // 在这个int数组上试验函数。    SetArray(p, 4, 5);    for (int i = 0; i < 10; ++i)    {        std::cout << nArray[i] << std::endl;    }    system("pause");} 

热点排行
Bad Request.