分享

typedef struct用法

 心不留意外尘 2016-06-06
http://blog.csdn.net/kirawoo/article/details/7439792
2012
typedef struct用法疑问
 
typedef struct node         /*链表节点定义*/
{ int a;
  struct node *next;
}LNode,*LinkList;

CreatJoseph(LinkList *jsp , int n)      /* 创建约瑟夫环*/
{.......}
insertList(LinkList *list, LinkList q, inte1, inte2)
{........}
LinkList已经是指针类型的,为什么还要LinkList *jsp  还要再加个"*"???

问题补充:

LinkList已经是指向结构体类型的指针了,直接LinkList jsp  为什么不对?jsp就是指向某个结构体的指针,为何还要在LinkList 后再加" * "??

 

2012-3-26 17:06
满意回答
弄明白指针变量与指针变量的值,局部变量和全局变量的关系
根据你说的情况,你只是在主调函数中定义了jsp但是并没有为其分配地址,所以你直接传进去的话存在冲突,要么变量没有被实例化,所以读入数据错误,
下面先以一个简单的结构体来说明
如:
typedef struct _INT 
{
	int a;
}INT, * pINT;

void f(pINT app);

int main(void)
{
	pINT a;
	f(a);

	printf("%d\n", *a);
	
	return 0;
}

void f(pINT app)
{
	app->a = 7;

	return ;
}
要么你在内部函数中实例化,但是你使用的指针变量,不是变量值所以造成内部函数使用的jsp作为局部变量,在被调函数执行完成后jsp不见了,虽然你分配的内存在,但是主调函数的jsp找不到被调函数为局部jsp所分配的地址,地址被浪费了,外部却没有找到。
#include <stdio.h>
#include <stdlib.h>

typedef struct _INT 
{
	int a;
}INT, * pINT;

void f(pINT app);

int main(void)
{
	pINT pa;
	f(pa);
	printf("p have fanished!\n");
	printf("%d\n", pa->a);
	
	return 0;
}

void f(pINT app)
{
	app = (pINT)malloc(sizeof(INT));
	app->a = 7;

	return ;
}

/*
p have fanished! 被输出后发生运行错误
*/


建议改正为在创建的时候穿参数为元素的个数就可以了
然后返回值是结构体的指针类型
如:
#include <stdio.h>
#include <stdlib.h>

typedef struct node         /*链表节点定义*/
{ 
	int a;
	struct node *next;
}LNode,*LinkList;

LinkList create(int num);
void traverse_list(LinkList jsp);

int main(void)
{
	LinkList jsp = create(5);

	traverse_list(jsp);
	traverse_list(jsp);
	
	return 0;
}

LinkList create(int num)
{
	LinkList pHead, tail, pNew;
	tail = pHead = (LinkList)malloc(sizeof(LNode));	//创建头结点
	tail->next = NULL;
	for(int i=0; i<num; i++)
	{
		pNew = (LinkList)malloc(sizeof(LNode));
		printf("Pls enter your %dth num: ", i+1);
		scanf("%d", &pNew->a);
		tail->next = pNew;
		tail = pNew;
	}
	tail->next = NULL;	//dont foget it
	return pHead;
}

void traverse_list(LinkList jsp)
{
	while(jsp->next != NULL)
	{
		jsp = jsp->next;
		printf("%d  ", jsp->a);
	}

	printf("\n");
}


而且从本程序我们也可以看见,在后面的两个traverse过程中都是引用jsp(LiskList型),但是外部的jsp并未被改变,所以你的那个好像是不对的 
运行结果为
Pls enter your 1th num: 1
Pls enter your 2th num: 2
Pls enter your 3th num: 3
Pls enter your 4th num: 4
Pls enter your 5th num: 5
1  2  3  4  5
1  2  3  4  5
Press any key to continue

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多