结构体例题输入函数问题

输入功能的子函数与主函数参数传递的类型示例:

#pragma pack(push)
#pragma pack(1)

#include<stdio.h>
#include<string.h>    

struct STI          
{
	char id[9];      
    char name[21]; 
	char sex;
	int age;
	int score;       
};

int inputStudentsInformation() ;

int inputStudentsInformation(struct STI s[20])    
{
	printf("inputStudentsInformation()里%d\n",sizeof(s));
	return 0;
}

void main(void)
{
	struct STI st[20];  
	int stCount = 0;
	printf("main()里%d\n",sizeof(st));
	stCount = inputStudentsInformation(st);   
}

#pragma pack(pop)

输出结果为:

这里的4说明子函数inputStudentsInformation() 里的形参传递的是首地址,故而只有4个字节。

(1)当把 s[20] 改为 s[1000] 时,输出结果一样;

(2)将函数定义中的int inputStudentsInformation(struct STI s[20])  改为 int inputStudentsInformation(struct STI *s) ,输出结果一样。

(2)将函数定义中的int inputStudentsInformation(struct STI s[20])  改为 int inputStudentsInformation(struct STI s[]) ,输出结果一样。

此时传递的就是首地址。

分析

int inputStudentsInformation(struct STI *s)

 

// struct STI *s = st <=> &st[0]  s的值为st[0]的首地址

// s指向main()函数的st数组的第一个元素,即下标为0的元素

// s+1指向main()函数的st数组的第二个元素,即下标为1的元素

// s+i指向main()函数的st数组的第i+1个元素,即下标为i的元素

// *s意为:s所指向的实例,即st[0]

// *(s+1)意为:s+1所指向的实例,即st[1]

// *(s+i)意为:s+1所指向的实例,即st[i]

// 综上,在inputStudentsInformation()函数中,可以通过s对main()函数中的st数组的所有元素(实例)进行访问(读和写/改/赋值)

 

主函数中stCount = inputStudentsInformation(st);

最终结论:
输入子函数定义:int inputStudentsInformation(struct STI *s) {}    

                            int inputStudentsInformation(struct STI s[]) {}       

主函数:stCount = inputStudentsInformation(st);  

              stCount = inputStudentsInformation(&st[0]);   

记忆:主函数传地址,子函数用指针

(传值还是传址,取决于函数的功能:若该函数需要更改其值,则传址;若不需要更改,则传值)


 

下面两种表述方式具有相同的效果:

(1)

int inputStudentsInformation(struct STI *s)
{
    int Cnt;
    //...
    return  Cnt;
}

void main(void)
{
    struct STI st[20];   
    int stCount = 0;

    stCount = inputStudentsInformation(st);
}

 

(2)

void inputStudentsInformation(struct STI *s, int *Cnt)
{
    //...
}

void main(void)
{
    struct STI st[20];   
    int stCount = 0;

    inputStudentsInformation(st, &stCount);
}

 

上述为输入函数,需要对输入的个数stCount进行更改,故传址;

但是对输出函数,仅仅只是输出,不需要对stCount进行更改,故传值

 

到底是传stCount还是&stCount,取决于函数的功能:

若该函数的功能要求更改stCount的值,则,传递&stCount;

若该函数的功能不要求更改stCount的值,则,传递stCount;

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安安csdn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值