C语言数据结构-1-指针、及参数的引用总结

  • 指针:存储的是内存的
int x ; 
int *p ;//声明为指针类型,int* 
*p=2 等同于 x = 2;都是为x赋值
  • 创建指针时,(静态)计算机将分配用来存储地址的内存,不会分配用来存储指针所指向的数据的内存。
  • 重要用途:在运行阶段(动态)分配未命名的内存以存储值,该值只能通过指针访问内存空间。
int *P = (int*)malloc(sizeof(int));
//p指向的时int的数据对象!而且系统分配了内存!
  • C语言的参数传递分为值传递、地址传递、C++中才能用&作为引用传递;参数传递其实每次进去都会复制传进去的值,地址传递为修改了地址所指向内存的值,所以修改了原变量;值传递修改的是复制的新的内存的值,所以没有修改输入的参数。

不能只靠传入的是不是指针来判断是值传递还是引用传递!!!!!可以手动复制去复制参数,看看操作的是不是传入的地址或者是其直接的值!!!!

比如:在判断链表的创建时,传入的时头指针,但是其实还是值传递,不是地址传递!!

下边的程序,首先在程序中复制了一个listPointer L = myL;然后又操作了L = p;这时,L已经指向P申请出的空间,不在指向myL;所以不行!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct listNode{
	int data;
	struct listNode* next;
}listNode, *listPointer;

void  createList(listPointer L)
{
	int x;
	//L头节点地址
	listPointer p;
	listPointer temp;
	//printf("%d", *x);

	p = (listPointer)malloc(sizeof(listNode));
	//这里的L其实是输入MyL复制的L,其实没有修改myL,是修改了L!!!
	(L) = p;
	printf("%s", "按序输入链表的值");
	scanf("%d", &x);
	while (x != 999)
	{

		temp = (listPointer)malloc(sizeof(listNode));

		temp->data = x;
		temp->next = NULL;
		p->next = temp;
		p = temp;

		scanf("%d", &x);
	}

}
void printList(listPointer L)
{

	while (L->next != NULL)
	{
		printf("%d ", L->next->data);
		L = L->next;
	}
}
int main()
{
	listPointer myL;
	myL = (listPointer)malloc(sizeof(listNode));
	createList(myL);
	printf("\n");
	printList(myL);
}

下边的程序为地址传递,listPointer *L = &myL;所以L指向myL,myL指向初始的Node;(*L)=p就是myL的值和p申请的值一样!myL指向p申请的内存空间,然后之后是对p的操作,所以myL可以生成链表!!!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct listNode{
	int data;
	struct listNode* next;
}listNode, *listPointer;

void  createList(listPointer *L)
{
	int x;
	//L头节点地址
	listPointer p;
	listPointer temp;
	//printf("%d", *x);

	p = (listPointer)malloc(sizeof(listNode));
	//L本来指向myL,现在相当于给myL赋值p
	(*L) = p;
	printf("%s", "按序输入链表的值");
	scanf("%d", &x);
	while (x != 999)
	{

		temp = (listPointer)malloc(sizeof(listNode));

		temp->data = x;
		temp->next = NULL;
		p->next = temp;
		p = temp;

		scanf("%d", &x);
	}

}
void printList(listPointer L)
{

	while (L->next != NULL)
	{
		printf("%d ", L->next->data);
		L = L->next;
	}
}
int main()
{
	listPointer myL;
	myL = (listPointer)malloc(sizeof(listNode));
	createList(&myL);
	printf("\n");
	printList(myL);
}

总结:具体的看是不是地址传递,看操作的内容!!!要传入是操作内容的指针/地址就行!

若操作的如上图所示为指针,所以传入应该为指针的指针。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值