6-03 2,109PVs
malloc()技巧,用指针的方式。
1 2 3 4 5 6 7 8 9 10 11 12 |
char *r ,*malloc(); r = malloc(strlen(s)+strlen(t)+1); //如果调用malloc()失败会反回NULL if(!r){ complain(); exit(1); } strcpy(r,s); strcat(r,t); //实现s和t的拼接 //一段时间之后再使用 free(r); |
使用指针遍历数组:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
in calendar[12][31]; int (* monthp)[31]; // *monthp是一个31个元素的数组 monthp=calendar; /*允许这样赋值是因为calendar是一个二维数组,也就是数组的数组,假如monthp不按照如上方式定义,而是单纯的定义为一个指针,则无法把calendar之内赋值。*/ /****常见遍历****/ int month; for (month=0;month<12;month++) { int day; for (day=0;day<31;day++) calendar[month][day]=0;// 此处等价于*(*(calendar + month)+day)=0; } /*****指针遍历****/ int (*monthp)[31]; for(monthp=calendar;monthp<&calendar[12];monthp++) { int *dayp; for(dayp=*monthp;dayp<&(*monthp)[31];dayp++) *dayp=0; } |
虽然数组和指针在大多数情况下其实是一样的,但是
1 2 3 4 5 6 |
extern char hello[0]; extern char * hello; //这情况下是不同的。 main(int argc, char * argv[]){} main(int argc, char ** argv){} //这两种情况下是一样的 |
如何对字符串进行快速修改?
1 2 3 4 |
int * q; q = 'abc'; q[1]='B'; //'abc'->'aBc' |
如何给数组赋值?
1 2 3 4 5 6 |
#define N 1024 static char buffer[N]; static char *bufptr = buffer; //bufptr初始化指向buffer头部 *bufptr++ =C; //把C赋给buffer第一个位置,然后bufptr+1,指向下一个未赋值区域 //初始化 bufptr=buffer; |
利用指针如何写一个自动填充buffer的函数?不用memcpy
1 2 3 4 5 6 7 8 |
bufwirte(char *p,int n) { while(--n>=0) //如果熟悉C语言执行顺序,就会理解--n>=0比等价的n-->0有可能还快 { if(bufptr==&buffer[N]) flushbuffer(); //写出buffer里的内容,并重置bufptr *bufptr++=*p++; } } |
利用指针写一个memcpy
1 2 3 4 5 |
void memcpy(char *dest,const char * source,int k) { while(--k>=0) *dest++=*source++; } |
如何提高bufwrite()函数的运行速度
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
void bufwrite(char *p,int n) { while(n>0) { int k,rem; if (bufptr==&buffer[N]) flushbuffer(); rem=N-(bufptr-buffer); memcpy(bufptr,p,k) bufptr+=k; p+=k; n-=k; } } |
Crayon这个代码高亮的插件怎么样,感觉好像还不错的样子 😉
很棒呀,哈哈
我之前就用这个,后来嫌加载多,又弃用了
习惯就好~~