8.结构体的使用 2015.12.3

***************************************************************************************************************************

8.结构体的使用  2012.3.20

***************************************************************************************************************************

#include "string.h"
#include "iostream"
using namespace std;

struct Student
{
	int sid;
	char name[20];
	int age;
};//结构体末尾分毫不能省略。。。

void main()
{
	struct Student st = {7911,"lose ",12};
	printf("%d %s    %d\n",st.sid,st.name,st.age);//控制输出的格式
	cout<<st.sid<<"    "<<st.name<<"    "<<st.age<<endl;//控制输出的格式
	
	//结构体中属性值的修改
	st.sid = 95287;
	//st.name = "lost all";//字符串的赋值不能这样的    error!!!
	strcpy(st.name,"lo");//字符串赋值的方式进行复制
	st.age = 99;
	printf("%d    %s    %d\n",st.sid,st.name,st.age);
}

 

struct Student st={1111111,"2222222",3333333}

struct Student *pst=&st;

则有:

st.sid=100

pst->sid=100    两种方式效果相同

************************************************************

#include "string.h"
#include "iostream"
using namespace std;

struct Student
{
	int sid;
	char name[20];
	int age;
};//结构体末尾分毫不能省略。。。


void f(struct Student *pst);//函数的方式对结构体进行赋值
void g1(struct Student st);
void g2(struct Student *st);

void main()
{
	struct Student st;
	cout<<"initial st    "<<&st<<endl;
	f(&st);
	//方法二输出:
	g2(&st);
	//方法一输出,特点是耗内存,耗时间
	g1(st);//相当于又开辟了一个内存空间

}

void f(struct Student *pst)
{
	//指针的方式进行赋值
	pst->sid=1111111;
	strcpy(pst->name,"pst_name");
	pst->age=200;
	cout<<"f *pst  "<<&(*pst)<<endl;
	cout<<"f  pst  "<<pst<<endl;//这里有指针的内容
//pst放的是指针的地址 是地址 *pst就是代表整个结构体的(不能直接输出的,cout<<*pst,error) &(*pst)是取出结构体(*pst)的首地址 这个值和pst存放的地址值是一样的。。。 } void g2(struct Student *st) { printf("%d %s %d \n",st->sid,st->name,st->age); st->sid = 666;//方法二中改变sid值 cout<<st->sid<<endl; cout<<"g2 *st "<<&(*st)<<endl; cout<<"g2 st "<<&st<<endl; } void g1(struct Student st) { printf("%d %s %d \n",st.sid,st.name,st.age); cout<<"g1 st "<<&st<<endl; //"在方法二种对sid的值进行修改,而二中的值并没有发生变化" }

 结果:

initial st    0012FF2C
   f *pst   0012FF2C
    f  pst   0012FF2C
1111111  pst_name  200
666
 g2 *st    0012FF2C
 g2  st    0012FEDC
666  pst_name  200
 g1  st    0012FEC4

posted @ 2015-12-04 10:10  不会水的水牛  阅读(118)  评论(0编辑  收藏  举报