最近正在看《C和指针》这本书,发现了一些之前没有关注过的问题,记录下来供自己参考。
1.计算一个字符串的长度
#include <stdio.h> #include <stdlib.h> #define TRUE 1 #define FALSE 0 size_t count_char(char *string) { int length; while(*string++ != '\0') length+=1; return length; } void main(void) { int temp; char ch[]= "wewe345435535^&&*45#5^46"; char ch1[]={'q','w','r','g'}; temp=count_char(ch); printf("%d\n" , temp); }
这个是直接可以用GCC编译器编译运行的。
2. 在字符串中查找一个特定的字符
#include <stdio.h> #define TRUE 1 #define FALSE 0 int find_char(char **strings , char value) { char *string; while((string=*strings++) != NULL) { while(*string != '\0'){ if(*string++ == value) return TRUE; } } return FALSE; } void main(void) { int temp=2; char *ch1[]={"do","while","if",NULL}; char g="if"; temp=find_char(*ch1, g); printf("the temp is %d",temp); }
这段代码是不能执行的,总是有错误,暂时没有发现错误点,分析find_char( )函数是 没有问题的,有问题的应该在main( )中,数组赋值出现问题。
3. 指针运算
#include <stdio.h> #define int unsigned int #define N_VALUES 5 float values[N_VALUES]={3.14,3.15,3.16,3.17,3.18}; float *vp; int main(void) { int i=0; /*while(i<N_VALUES){ printf("the previous i is %d\n",i); printf("%f\n",values[i++]); printf("the back i is %d\n",i); }*/ for(vp = &values[0]; vp < &values[N_VALUES]; ) { //printf("the &values[] is %f\n ", vp); //printf("the values[] is %f\n ", *vp); *vp++=0; printf("the values is %f\n ", *(vp-1)); printf("the values is %f\n ", *vp); } while(i<N_VALUES){ printf("%f\n",values[i++]); } }
运行后的结果:the values is 0.000000
the values is 3.150000
the values is 0.000000
the values is 3.160000
the values is 0.000000
the values is 3.170000
the values is 0.000000
the values is 3.180000
the values is 0.000000
the values is 0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
符合函数的预期功能。