C语言 指针与结构体

结构体指针

# include <stdio.h>//引用函数库
# include <stdlib.h>
struct info{
	char name[4];
	int age;
};
void main(){
	struct info student1;
	student1.age = 19;
	sprintf(student1.name,"li");
	printf("%d,%s\n",student1.age,student1.name);

	struct info *p;//p存储地址,struct info决定内存长度
	p=&student1;
	printf("%d,%s\n",(*p).age,(*p).name);//指针访问结构体第一种方法
	printf("%d,%s\n",p->age,p->name);//指针访问结构体第二种方法
}

结构体数组指针

# include <stdio.h>//引用函数库
# include <stdlib.h>
struct info{
	char name[10];
	int age;
};
void main(){
	struct info student1[2]={"li",18,"lu",17};
	for (struct info *p =student1;p<student1+2;p++){
		printf("%s,%d\n",p->name,p->age);
		printf("%s,%d\n",(*p).name,(*p).age);
	}
}

结构体指针作为参数

# include <stdio.h>//引用函数库
# include <stdlib.h>
struct info{
	char name[10];
	int age;
};
change(struct info *p){
	p->age=10;
}
void main(){
	struct info student1={"li",18};
	change(&student1);
	printf("%d",student1.age);
}

结构体数组作为参数

# include <stdio.h>//引用函数库
# include <stdlib.h>
struct info{
	char name[10];
	int age;
};
change(struct info student[]){//函数参数传递的是数组的地址,而不是新建了一个数组
	student[1].age=100;
}
void main(){
	struct info student1[2]={"li",18,"lu",17};
	change(&student1);
	printf("%d",student1[1].age);
}

动态分配结构体内存

# include <stdio.h>//引用函数库
# include <stdlib.h>
struct info{
	char name[10];
	int age;
};
void main(){
	struct info *p=(struct info *)malloc(sizeof(struct info)*2);//malloc返回的是void类型指针,所以要强转
	for (int i =0;i<2;i++){//指针数组
		p[i].age=i*10;
		printf("%d ",p[i].age);
	}
	for (int i =0;i<2;i++){//指针
		(*(p+i)).age=i*10;
		printf("%d ",(*(p+i)).age);
	}
	for (struct info *pp=p;pp<p+2;pp++){//指针轮循
		(*pp).age=10;
		printf("%d ",(*pp).age);
	}
}
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值