这里不得不多说一句,对于c来说指针我认为最好用的就是链表,有很多实用的地方
#include<string.h>
#include<stdio.h>
//C语言 链表篇
//结构体实现单向链表
struct MyStruct
{
char name[20];
struct MyStruct *before;
};
void test6()
{
int a = 0;
//原理演示
//链表头 作为一个空结构体 表示找到头了 结束回溯
static struct MyStruct *list_head = NULL;
struct MyStruct mt = {"songyu",list_head};
struct MyStruct mt2 = { "zhanghaimi",&mt};
struct MyStruct mt3 = { "xuqiu",&mt2 };
struct MyStruct temp = mt3;
while (temp.before != NULL)
{
printf("before name is:%s\n", temp.name);
temp = *temp.before;
}
//动态申请 添加链表
struct MyStruct *tempp = NULL;
int j = 0;
char inputname[20];
const char exist[] = "ok";
typedef struct MyStruct MS; //重命名,便于书写,太长了struct node
typedef struct MyStruct* MSPoint;
MSPoint head = NULL;//head指向NULL 防止野指针
MSPoint temp1;
while (j < 3)
{
MSPoint p = (MSPoint)malloc(sizeof(MS)); //malloc()函数分配Node大小的空间,类型转换为Link型,指赋给p
if (p == NULL)//空间分配失败
{
printf("malloc error!\n");
exit(-1); //结束进程 文件包含stdlib.h
}
printf("请输入姓名:");
scanf("%s", &inputname);
if (strcmp(inputname, exist)==0)
{
break;
}
strcpy(p->name, &inputname);
if (j == 0)
{
p->before = head;
}
else
{
p->before = temp1;
}
temp1 = p;
j++;
}
//定义结构体指针,访问成员时就用->
//定义结构体变量,访问成员时就用.
for (j=3; j > 0; j--)
{
printf("now value is :%s before address is :%d \n", temp1->name, temp1->before);
temp1 = temp1->before;
}
//使用malloc方法 申请固定内存 动态添加链表元素
gets();
gets();
}