数据结构

一些基础知识:

double *p;
double x = 1.1;
p = &x;

1.一个字节是8位,一个字节一个地址;但是p存放的是一个地址了,一般存放的是首字节的地址。
2.无论指针变量指向的变量占几个字节,指针变量都是占四个字节。

结构体:
1.结构体是重新定义了一个数据类型,把同类的都放在了一起。eg:

struct  Student 
{
	int sid;
	char name[200];
	int age;
};	//	分号不能少

上面就定义了一个叫做struct Student的数据类型。
如果用的时候,就:

int main(void)
{
	struct Student st = {1000"zhangsan",20} ;//定义叫st的变量,并完成初始化
	或者如果单独初始化,那就是:
	st.sid = 1000;
	strcpy(st.name,"lisi");// c语言里符号不能能直接赋值,得用strcpy函数;
	st.age = 20;
	printf("%d  %s %d",st.sid,st.name,st.age);
}

2.如果想用结构体里面的变量,还有一种方式是用指针:

	struct Student st = {1000"zhangsan",20} ;//定义叫st的变量,
	struct Student *pst //定义一个struct Student类型的指针pst;
	pst = &st;//pst保存st的地址;
	pst->sid = 1000;//pst->sid 等价于(*pst).sid ,而(*pst).sid 等价于st.sid,因此pst->sid等价于st.sid

3.结构体变量不能加减乘除,但是可以相互赋值;
普通结构体变量和结构体指针变量可以作为函数传参

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

struct Student 
{
    int sid;
    char name[200];
    int age;
};

void f(struct Student *pst);
void g(struct Student st);
void g2(struct Student *pst);

int main(void)
{
    struct Student st;
    f(&st);
   // g(st);
    g2(&st);
    //printf("%d %s %d",st.sid,st.name,st.age);
	return 0;
}

void f(struct Student *pst)
{
    (*pst).sid = 99;
    strcpy(pst->name,"zhangsan");
    pst->age = 22;
}

void g(struct Student st)
{
    printf("%d %s %d",st.sid,st.name,st.age);
}

void g2(struct Student *pst)
{
    printf("%d %s %d",pst->sid,pst->name,pst->age);
}

动态分配数组长度:
malloc函数:动态分配一块内存出来,并且传回这愉快字节的第一个字节的地址。
动态分配内存的好处:
1.可以根据程序实际运行,自由分配内存;
2.可以把使用的动态内存释放掉;

#include <stdio.h>
#include <malloc.h>
int main(void)
{
    int a[5] = {2,4,6,8,10};
    
    int len ;
    scanf("%d",&len);
    int *pArr = (int *)malloc(sizeof(int)*len);
    *pArr = 2;//    类似于a[0] = 2;
    pArr[1] = 4;    // 类似于a[1] = 4;
    printf("%d %d %d\n",*pArr,pArr[1],*(pArr+1));
    free(pArr);// 把pArr所代表的动态分配的20个字节的内存释放掉
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值