08结构体与C++引用讲解作业
一、上节作业(重点)
-
输入一个学生的学号,姓名,性别,用结构体存储,通过scanf读取后,然后再通过printf打印输出
#include <stdio.h>
//struct student{
// int num;
// char name[20];
// char sex;
//};
typedef struct student{
int num;
char name[20];
char sex;
}stu;
int main() {
// struct student s;
stu s;
scanf("%d%s %c",&s.num,s.name,&s.sex);
printf("%d %s %c\n",s.num,s.name,s.sex);
return 0;
}
-
使用C++的引用,注意提交时把代码选为C++;在主函数定义字符指针 char *p,然后在子函数内malloc申请空间(大小为100个字节),通过fgets读取字符串,然后在主函数中进行输出;要求子函数使用C++的引用,注意在C++中从标准输入读取字符串,需要使用fgets(p,100,stdin)。
#include <stdio.h>
#include <stdlib.h>
void get_char(char *&p){//当在子函数中要修改主函数的p,那么就要加引用
p=(char*)malloc(100);
fgets(p,100,stdin);
}
int main() {
char *p=NULL;
get_char(p);
puts(p);
free(p);//申请的空间不使用后,需要free
return 0;
}
初级阶段完结!