C语言指针类型数据++操作探究
起因是Csapp第三版,5.17,自己手动实现高级memset函数
代码如下:
#include<stdlib.h>
#include<cstdio> #include<iostream> #include<stack> #include<ctime> #include<cmath> #include<windows.h> #include<vector> #include<map> #include <limits.h> using namespace std; void *my_memset(void *s, int c, size_t n) { size_t K=sizeof(unsigned long); if(n<K) { size_t cnt = 0; unsigned char *schar = (unsigned char *)s; while (cnt < n) { *schar++ = (unsigned char)c; cnt++; } } else { unsigned long comb=0; for (int i=1;i<=K;i++) { comb<<=CHAR_BIT; comb+=(unsigned char)c; } size_t cnt = 0; unsigned long *slong = (unsigned long *)s; while (cnt+K<=n) { *slong=comb; slong+=1; cnt+=K; } unsigned char *schar =(unsigned char *)slong; while(cnt<n) { *schar++ = (unsigned char)c; cnt++; } } return s; } int main() { char a[15]; my_memset(a,65,sizeof(a)); cout<<a<<endl; memset(a,65,sizeof(a)); cout<<a<<endl; system("pause"); }
关注
这段代码,slong是unsigned long *类型的指针。
我们想要指针指向范围跨越sizeof(unsigned long),直接++,就能实现。不需要slong+=sizeof(unsigned long)