一、结构体值传递
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
struct Aiyou
{
int year;
char* name;
char* zdg;
};
//声明一个函数setaiyou,参数是一个指针
void setaiyou(struct Aiyou aayy)
{
printf("专辑名称:%s,主打歌:%s,发行时间:%d\n", , aayy.zdg, aayy.year);
}
int main() {
struct Aiyou ay;
ay.year = 2016;
= "周杰伦的床边故事";
ay.zdg = "告白气球";
printf("专辑名称:%s,主打歌:%s,发行时间:%d\n", , ay.zdg, ay.year);
//调用该函数,将ay对象传递过去
setaiyou(ay);
system("pause");
return 0;
}
运行结果:
二、结构体地址传递
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
struct Aiyou
{
int year;
char* name;
char* zdg;
};
void setaiyou( const struct Aiyou *p)
{
printf("专辑名称:%s,主打歌:%s,发行时间:%d\n", p->name, p->zdg, p->year);
}
int main() {
struct Aiyou ay;
ay.year = 2016;
= "周杰伦的床边故事";
ay.zdg = "告白气球";
printf("专辑名称:%s,主打歌:%s,发行时间:%d\n", , ay.zdg, ay.year);
setaiyou(&ay);
system("pause");
return 0;
}
1、const struct Aiyou *p
const 修饰 *,指针指向的内存不能修改,例如:p->year=2015,编译就会报错
2、struct Aiyou * const p
const 修饰p,指针不能修改,例如:p=NULL,编译就会报错
运行结果:
三、结构体在堆区分配空间
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
struct Aiyou
{
int year;
char* name;
char* zdg;
};
int main() {
struct Aiyou *ay;
ay = (struct Aiyou *)malloc(sizeof(struct Aiyou));
if(ay==NULL)
{
pritf("分配内存失败");
return 0;
}
ay->year = 2016;
ay->name = "周杰伦的床边故事";
ay->zdg = "告白气球";
printf("专辑名称:%s,主打歌:%s,发行时间:%d\n", ay->name, ay->zdg, ay->year);
if(ay!=NULL)
{
free(ay);//释放内存
p=NULL;
}
system("pause");
return 0;
}
运行结果:
三、成员指针在堆区分配空间
ay.zdg = (char*)malloc(strlen("告白气球")+1);
strcpy_s(ay.zdg,10,"告白气球");