1.定义一个数组:
数组里面的每一个元素代表一个学生:
1.1第一种定义方式:直接声明一个指针指向数组。
struct Student stus[3];
struct Student *p = stus;
1.2第二种定义方式:用指针指向malloc开辟一个数组空间,数组的另一种定义方式。
struct Student *p;
p = (struct Student *)malloc(3 * sizeof(struct Student));
2.具体代码如下:(注意指针的偏移,即是p++之后再次使用是否要回到数组头)
#include <stdio.h>
#include <stdlib.h>
struct Student
{
int score;
char *name; //4 linux 8
};
int main()
{
int i;
int len = 0;
printf("请输入总人数:\n");
scanf("%d",&len);
struct Student *p = (struct Student *)malloc(len*sizeof(struct Student));
for(i=0;i<len;i++){
printf("请输入名字:\n");
p->name = (char *)malloc(128);
scanf("%s",p->name); //name是指针,指针指向的就是地址,所以不用取地址
printf("请输入分数:\n");
scanf("%d",&(p->score)); //取地址有括号是优先级的问题
p++;
}
//p = stus; // *只有在指针变量声明的时候才代表指针的符号, 其他的位置有*代表的是运算符,取值
// 这里的意思是让指针指向stus的头 ,因为上面p++已经指向了函数的尾巴,下面for循环会空,什么都没有
p = p - len; //上面p++已经指向了函数的尾巴,这里是让函数回到首位
for(i=0;i<len;i++){
printf("名字:%s,分数:%d\n",p->name,p->score);
p++;
}
system("pause");
return 0;
}