大鸽的代码箱:关于全局变量与局部变量的思考:C语言习题7-9(谭浩强第四版)

代码问题

问题描述

1.程序能够正常运行,在void中运行的blank,number,number,ab始终显示为0;
2.没有弄清楚全局变量到底运用于什么情况?

解决方案

1问题原因:错误定义了全局变量的位置;局部变量(auto变量)在函数结束后会自动释放存储空间,所以一定是0;
2.全局变量运用于那些主函数和子函数都需要且最后需要输出的值,全局变量的意思就是在该系列所有函数都定义了的变量,运行于主程序的完整流程的变量。
切记两点:
(1)全局变量不是在主函数中定义的!!!注意位置
(2)在子函数中不要在额外定义了,全局变量与局部变量冲突且不报错详见错例第一行
ps:不要过分纠结这一块,学完指针啥都明白了。

void friday3(int blank, int number, int other, int ab, char t1[])//形参不能乱定义的
{
	int m;
	int i;
	m = zifushu(t1);
	for (i = 0; i < m; i++)
	{
		if ((t1[i] >= 'a' && t1[i] <= 'z') || (t1[i] >= 'A' && t1[i] <= 'Z'))
			ab++;
		else if (t1[i] >= '0' && t1[i] <= '9')
			number++;
		else if (t1[i] == ' ')
			blank++;
		else
			other++;
	}
}

# include <stdio.h>
int main(void)
{
	char t1[1000];
	int blank = 0, number = 0, other = 0, ab = 0;//主函数定义的不是全局变量
	gets_s(t1);
	void friday3(int blank, int number, int other, int ab, char t1[]);
	friday3(blank, number, other, ab, t1);//调用形参单元被释放,实参单元被保留
	printf("%d%d%d%d\n", blank, number, ab, other);
	return 0pp

下面展示 修正的

# include <stdio.h>
int blank,number,other,ab;

void friday3(char t1[])
{
	int m;
	int i;

	for (i = 0; t1[1]!='\0'; i++)//优化写法
	{
		if ((t1[i] >= 'a' && t1[i] <= 'z') || (t1[i] >= 'A' && t1[i] <= 'Z'))
			ab++;
		else if (t1[i] >= '0' && t1[i] <= '9')
			number++;
		else if (t1[i] == ' ')
			blank++;
		else
			other++;
	}
int main(void)
{
	char t1[1000];
	gets_s(t1);
	blank = 0, number = 0, other = 0, ab = 0;
	void friday3(char t1[]);
	friday3(t1);
	printf("%d %d %d %d\n", blank, number, ab, blank);
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值