核心观点:
- 单个结构体是不能写成“指针名 = 结构体变量名”;
- 结构体数组却可以写成“指针名 = 结构体变量名” 。
观点1论证:单个结构体是不能写成“指针名 = 结构体变量名”的, 例如 pstu = stu1 是错误的,必须写成 pstu = &stu1 。
见下面的程序
#include <stdio.h>
int main(){
struct stu{
char *name; //姓名
int num; //学号
int age; //年龄
char group; //所在小组
float score; //成绩
} stu1 = { "Tom", 12, 18, 'A', 136.5 };
//单个结构体是不能写成“指针名 = 结构体变量名”的, 例如 pstu = stu1 是错误的,必须写成 pstu = &stu1
struct stu *pstu;
pstu = &stu1;
//读取结构体成员的值
printf("%s的学号是%d,年龄是%d,在%c组,今年的成绩是%.1f!\n", (*pstu).name, (*pstu).num, (*pstu).age, (*pstu).group, (*pstu).score);
printf("%s的学号是%d,年龄是%d,在%c组,今年的成绩是%.1f!\n", pstu->name, pstu->num, pstu->age, pstu->group, pstu->score);
return 0;
}
观点2论证:但是结构体数组却可以写成“指针名 = 结构体变量名” 。
见下面的程序
#include <stdio.h>
#include <stdlib.h>
#include "string.h"
#include "io.h"
#include<iostream>
using namespace std;
struct stu{
char *name; //姓名
int num; //学号
int age; //年龄
char group; //所在小组
float score; //成绩
}stus[] = { //stus 是个结构体变量
{ "Zhou ping", 5, 18, 'C', 145.0 },
{ "Zhang ping", 4, 19, 'A', 130.5 },
{ "Liu fang", 1, 18, 'A', 148.5 },
{ "Cheng ling", 2, 17, 'F', 139.0 },
{ "Wang ming", 3, 17, 'B', 144.5 }
}; //ps 是个结构体变量指针
//但是结构体数组却可以写成“指针名 = 结构体变量名”
int main(){
//求数组长度
int len = sizeof(stus) / sizeof(struct stu);
struct stu *ps;
cout << stus << endl; //直接输出 stus 是一个地址,ps是一个指针,和地址一样,
//ps++ 因为ps是 struct stu 型结构体指针,所以ps++ 等价于ps的地址增加了20
printf("Name\t\tNum\tAge\tGroup\tScore\t\n");
//len = 5
for (ps = stus; ps<stus + len; ps++){
cout << ps << endl;
//printf("%s\t%d\t%d\t%c\t%.1f\n", ps->name, ps->num, ps->age, ps->group, ps->score);
}
return 0;
}