这是整理的以前学习的笔记拿出来分享一下。有错误之处还请给予批评指出。
在学习结构体之前先学习一下指针。下面两个关于指针的例子,对我帮助挺大的。注释也很清晰。刚开始学指针的时候晕了好久。总是搞不清楚谁指向谁,谁是谁的地址。
# include <stdio.h>
void f(int * p)
{
*p = 100;//p保存了i的地址,*p = i
}
int main(void){
int i = 9;
f(&i);
printf("i = %d\n", i);
return 0;
}
指针变量统一只占4个字节。与它指向的变量无关。指针变量保存的只是数据类型所占字节的第一个字节。而不是这个数据类型所占的所有字节。这点很重要。下面的例子证明了这个问题。
# include <stdio.h>
int main(void)
{
double * p;
double x = 23.5;
p = &x; //x占8个字节 1个字节是8位,1个字节一个地址,p存放的是第一个字节的地址,不是存放的是8个字节的地址
double arr[5] ={1.3,2.5,3.4,4.2,4.5};
double * q;
q = &arr[0];
printf("%p\n", q);//%p实际上就是以十六进制输出.指针变量统一只占四个字节。与它指向的变量无关
q = &arr[1];
printf("%p\n", q);
return 0;
}
接下来重点看看结构体。
1.什么是结构体:为了表示一些复杂的数据,而普通的基本类型无法满足要求。用户根据实际需要自己定义的复合数据类型。结构体也是一种数据类型,只是是自己定义的而已。例如:定义一个Student类型。
struct Student
{
int sid;
char name[200];
int age;
};
//定义了一个学生类型,是一个数据类型。包涵了3个成员。类型是:struct Student
你会发现它和Java的类很相似。但是结构体中不能有方法。它更像Java中的实体。
2.怎样访问结构体:结构体变量的名字.成员名
下面通过一个例子来说明吧!
第一种赋值方式:
# include <stdio.h>
# include <string.h>
//定义了一个学生类型,是一个数据类型。包涵了3个成员。类型是:struct Student
struct Student
{
int sid;
char name[200];
int age;
};
int main(void)
{
struct Student st = {2000,"hanyahui",22};
printf("%d %s %d\n",st.sid,st.name,st.age);
//给结构体成员赋值
st.sid = 1000;
strcpy(st.name,"Love,you");
st.age = 18;
printf("%d %s %d\n",st.sid,st.name,st.age);
return 0;
}
第二种赋值方式:
# include <stdio.h>
# include <string.h>
//定义了一个学生类型,是一个数据类型。包涵了3个成员。类型是:struct Student
struct Student
{
int sid;
char name[200];
int age;
};
int main(void)
{
struct Student st = {2000,"hanyahui",22};
//st.sid = 33;//一般不这样用
struct Student * pst;
pst = &st;
pst->sid = 34;//pst->sid 等价于(*pst).sid这是一种规定,而(*pst).sid等价于st.sid,所以pst->sid等价于st.sid
//pst->sid表示:pst所指向的结构体变量中的sid这个成员
return 0;
}
下面这个例子来说明结构体传值问题:
# include <stdio.h>
# include <string.h>
/*
通过函数修改结构体中成员的值
*/
void f(struct Student * p);
void prin(struct Student st);
void prin2(struct Student * pst);
struct Student
{
int sid;
char name[200];
int age;
};
int main(void)
{
struct Student st = {2000,"hanyahui",22};
f(&st);
prin(st);
prin2(&st);
//printf("%d %s %d\n",st.sid,st.name,st.age);一般通过一个函数输出
return 0;
}
//这种方式不推荐使用,耗内存,耗时间。因为传递的是整个结构体变量
void prin(struct Student st)
{
printf("%d %s %d\n",st.sid,st.name,st.age);
}
//通过指针传递,推荐使用
void prin2(struct Student * pst)
{
printf("%d %s %d\n",pst->sid, pst->name, pst->age);
}
void f(struct Student * pst)
{
(*pst).sid = 99;
strcpy(pst->name,"hanyahui");
pst->age = 22;
}
以上内容也没有好好整理。只是做了个笔记。也希望能帮助需要的人。