结构体例题输入函数问题

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

#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;

猜你喜欢

转载自blog.csdn.net/weixin_42072280/article/details/82597663