记一次C语言指针的学习

#include <stdio.h>
#include <string.h>
#define M1 "How are ya, sweetie? "
char M2[40] = "Beat the clock.";
char * M3 = "chat";
int main()
{
	char words[80];
	printf(M1);			//How are ya, sweetie? How are ya, sweetie?
	puts(M1);			
	puts(M2);			//Beat the clock.
	puts(M2 + 1);		//eat the clock.
	strcpy(words, M2);	//words == "Beat the clock."
	strcat(words, "Win a toy.");//words == "Beat the clock.Win a toy."
	puts(words);				//Beat the clock.Win a toy.
	words[4] = '\0';			
	puts(words);				//Beat
	while (*M3)					
		puts(M3++);				//chat
	puts(--M3);					//hat 
	puts(--M3);					//at
	M3 = M1;					//t
	puts(M3);					//t
	return 0;					//at
}								//How are ya, sweetie? 

要点:while循环中puts是输出指针的字符字符串

#include <stdio.h>
#include <string.h>
#define M1 "How are ya, sweetie? "
char M2[40] = "Beat the clock.";
char * M3 = "chat";
int main()
{
	char str1 [] = "gawsie";
	char str2 [] = "bletonism";
	char *ps;
	int i = 0;
	for (ps = str1; *ps != '\0'; ps++)//ps == "gawsie"
	{
		if (*ps == 'a' || *ps == 'e')
			putchar(*ps);
		else
			(*ps)--;
		putchar(*ps);         //faavrhee
	}
	putchar('\n');
	while (str2[i] != '\0')
	{
		printf("%c", i % 3 ? str2[i] : '*');//*le*on*sm
		++i;
	}

	return 0;					
}								

复习条件运算符与取余符号%:
条件运算符当?前取得的值判断为真时,结果为:前的值,当?前取判断的值为假时,结果为:后的值
取余符号的几个例子:

#include <stdio.h>
int main(void)
{
	printf("%d", 0 % 3);//结果为0
	printf("%d", 1 % 3);//结果为1
	printf("%d", 2 % 3);//结果为2
	
	return 0;
}

改写《C primer plus》中的s_gets()函数,用指针表示法代替数组表示法便可减少一个变量i

原s_gets函数
char * s_gets(char * st, int n)
{
	char * ret_val;
	int i = 0;

	ret_val = fgets(st, n, stdin);//fgets函数把换行符放在字符串的末尾
	if (ret_val)
	{
		while (st[i] != '\n' && st[i] != '\0')
			i++;
		if (st[i] == '\n')
			st[i] = '\0';
		else
			while (getchar() != '\n')
				continue;
	}
	return ret_val;
}

改写之后

char * s_gets(char * st, int n)
{
	char * ret_val;

	ret_val = fgets(st, n, stdin);
	if (ret_val)
	{
		while (*st != '\n' && *st != '\0')
			st++;
		if (*st == '\n')
			*st = '\0';
		else
			while (getchar() != '\n')
				continue;
	}
	return ret_val;
}

与答案给出的解法相同

用strchr()函数代替其中的while循环来查找换行符

char * s_gets(char * st, int n)
{
	char * ret_val;
	char * find;
	int i = 0;

	ret_val = fgets(st, n, stdin);
	if (ret_val)
	{
		find = strchr(st, '\n')
		if (find)
			*find = '\0'
		else
			while (getchar() != '\n')
				continue;
	}
	return ret_val;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值