//26. 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>
using namespace std;
void main() {
int a[5]={0};
void *p;
p = static_cast<void*>(&a[1]); //一个void* 似乎只能指向一个数组的首地址,而且它的大小就是4
void func(void*,int,int);
func(p,2,1);
cout<<a[1]<<endl;
}
void func(void *vp,int num,int val) { //void指针,要修改的字节数,要修改的值
/* 也可以这样写:
int *ip= static_cast<int*>(vp);
*ip>>=num*8;
*ip<<=num*8;
*/
/*关于一下写法请参看P169的笔记:
要改变void指针所指向的数据,则:
void* vp;
*((float*)vp)=3;
先cast再赋值
*/
*(static_cast<int*>(vp))>>=num*8;
*(static_cast<int*>(vp))<<=num*8; //将数值右移num个字节,再左移num个字节,达到清零的目的
for(int i=1;i<=num;i++) { //将数值与要修改的值按位或,要修改的值每次向左移动1个字节,达到所需要字节都被修改的目的
*(static_cast<int*>(vp)) |= val<<(i-1)*8;
}
}
//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>
using namespace std;
void main() {
int a[5]={0};
void *p;
p = static_cast<void*>(&a[1]); //一个void* 似乎只能指向一个数组的首地址,而且它的大小就是4
void func(void*,int,int);
func(p,2,1);
cout<<a[1]<<endl;
}
void func(void *vp,int num,int val) { //void指针,要修改的字节数,要修改的值
/* 也可以这样写:
int *ip= static_cast<int*>(vp);
*ip>>=num*8;
*ip<<=num*8;
*/
/*关于一下写法请参看P169的笔记:
要改变void指针所指向的数据,则:
void* vp;
*((float*)vp)=3;
先cast再赋值
*/
*(static_cast<int*>(vp))>>=num*8;
*(static_cast<int*>(vp))<<=num*8; //将数值右移num个字节,再左移num个字节,达到清零的目的
for(int i=1;i<=num;i++) { //将数值与要修改的值按位或,要修改的值每次向左移动1个字节,达到所需要字节都被修改的目的
*(static_cast<int*>(vp)) |= val<<(i-1)*8;
}
}