怎样用函数初始化结构体

问题

这里主要讨论函数的参数,应该是结构体呢,还是结构体的地址,还是二者都行。

实验证明,只能用结构体的地址。


代码

#include<stdio.h>
#include<math.h>
#include<stdlib.h>

typedef struct 
{
  int a;   //"int a=0;" is wrong
  int b[10];    
}STU;


void init_struct_point(STU *s){		//参数为数组指针
	s->a=100;
	s->b[0]=5;
	s->b[1]=7;

	printf("in f_point(), s->a  %d\n",s->a);
	printf("in f_point(), s->b[0]  %d\n\n",s->b[0]);
}


void init_struct(STU s){			//参数为数组
	s.a=1;
	s.b[0]=2;
	s.b[1]=3;

	printf("in f(), s.a  %d\n",s.a);
	printf("in f(), s.[0]  %d\n\n",s.b[0]);
}



int main(){
    STU s;

	printf("s=%d \t &s=%d\n\n",s,&s);


	init_struct_point(&s);	//"s1"会引发编译错误

	printf("s=%d \t &s=%d\n\n",s,&s);


    printf("out f_point(), s.a  %d\n",s.a);
	printf("out f_point(), s.b[0]  %d\n",s.b[0]);
	printf("out f_point(), s.b[1]  %d\n\n",s.b[1]);



	init_struct(s);		//"&s1"会引发编译错误

    printf("out f(), s.a  %d\n",s.a);
	printf("out f(), s.b[0]  %d\n",s.b[0]);
	printf("out f(), s.b[1]  %d\n\n",s.b[1]);


 
    system("pause");
	 return 0;   
}



运行结果


遗留问题

1.结构体变量名究竟是什么,请看s以及&s?

2.结构体变量名 和 结构体数组变量名 有什么区别和联系? http://blog.csdn.net/hiboy_111/article/details/44454149



发布了60 篇原创文章 · 获赞 20 · 访问量 3万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章