指向指针数组的指针
先来一段代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Student{
int sno;
char sname[20];
int age;
};
struct node{
Student data;
node* next;
};
char** minimum_age(node* phead);
int main()
{
node* phead = NULL,* miniphead = NULL;
node* pnew = NULL;
printf("输入信息(学号为0时停止):\n");
while(1)
{
pnew = (node*)malloc(sizeof(node));
if(pnew != NULL)
{
printf("\n学号:"); scanf("%d",&pnew->data.sno);
if(pnew->data.sno == 0) break; fflush(stdin);
printf("姓名:"); scanf("%s",&pnew->data.sname);
printf("年龄:"); scanf("%d",&pnew->data.age);
pnew->next = NULL;
if(phead == NULL) phead = pnew;
else{
node* p = phead;
while(p->next) p = p->next;
p->next = pnew; }
}
}
char** name = minimum_age(phead);
while(*name)
{
printf("%s ",*name);
name++;
}
return 0;
}
char** minimum_age(node* phead)
{
if(!phead) return NULL;
int min = phead->data.age ;
int count = 0;
for(node* p = phead;p;p = p->next,count++ )
if(p->data.age < min) min = p->data.age;
char** name = (char**)malloc(sizeof(char*)*(count+1));
int i = 0;
for(node* p = phead;p;p = p->next)
{
if(p->data.age == min){
*(name+i) = (char*)malloc(sizeof(p->data.sname));
strcpy(*(name+i),p->data.sname );
i++;
}
}
*(name+i) = NULL;
return name;
}
这个代码实现的是寻找年龄最小的学生名单(包括重复)
自定义函数返回的类型是char ** 也就是指向指针的指针
if(!phead) return NULL;
这行代码考虑了如果链表一个学生都没有的情况,返回NULL;
int min = phead->data.age ;
int count = 0;
for(node* p = phead;p;p = p->next,count++ )
if(p->data.age < min) min = p->data.age;
这段代码是在链表中有学生的情况下找到最小年龄min,同时记录了一共有多少学生
char** name = (char**)malloc(sizeof(char*)*(count+1));
申请了有count+1个房间的指针数组,count+1的原因是如果链表中所有学生年龄一致,那么申请的指针数组如果为count个房间,那么将无法将NULL存入最后一个房间,那么在返回这个数组时就无法知道结束标记,count + 1是为了在所有学生年龄一致(几率虽然很小但不能排除)时能够在第count + 1中存入NULL这个结束标记。
同时定义了一个指向指针数组的指针指向申请的指针数组(有点绕)
上图:
最后让*(name+i)=NULL;指空。
画图会明白一些。