C语言----指针

最近正在看《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

符合函数的预期功能。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值