[C Language] Frequently Asked Questions about Passing Pointers as Parameters

 1. Pointer definition:

        Pointers are an important concept and feature in C language, and they are also a difficult part of mastering C language. Pointers are storage addresses . Pointer variables are variables used to store memory addresses. Under the same CPU architecture, the length of storage units occupied by different types of pointer variables is the same, while variables that store data vary depending on the type of data. The length of storage space occupied is also different. With pointers, you can not only operate on the data itself, but also on the variable address where the data is stored.

        The pointer describes the location of data in memory, marking an entity occupying storage space and the relative distance value from the starting position of this space. In the C/C++ language, pointers are generally considered to be pointer variables. The content of a pointer variable stores the first address of the object it points to. The object pointed to can be a variable (pointer variables are also variables), arrays, functions, etc. occupy storage space. entity.

2. Problems encountered:

This morning when I was reviewing singly linked lists in C language, I encountered a problem of not being able to get the value when assigning values, which made me very confused.

        I looked at it carefully several times later and found that what I wanted to do was to assign a value to the pointer. Logically speaking, I should pass the address of the pointer in. I naively thought that the pointer I passed in was the address, wasn't it? actually not, 

        For example: int a=0; int * p=&a;

        The pointer variable we pass in is actually the address of the variable it points to, so if I am operating on the value of a, then I can just pass the value of the pointer variable in. But if what I want to operate is the value of p, then I have to pass the address of p.

        For the above problem, I should change the method to:

        bool  InitList(LinkList &L);

        bool  Empty(LinkList &L);

 Code:

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

/**
	定义链表存储结构 
*/
typedef struct LNode{
	int data;
	LNode *next;
}LNode,*LinkList;
int main(){
	bool InitList(LinkList &L);//声明 
	bool Empty(LinkList &L);//声明
	//先有变量再用指针,不然指针会指向一个我们不希望的地方 
//	LNode L;
	LinkList p=NULL;
	InitList(p);
	printf("成功初始化\n");
	Empty(p);
	 
	return 0;
}

/**
	初始化带头结点的链表 
*/ 
 bool InitList(LinkList &L){
 	L=(LNode*)malloc(sizeof(LNode));
 	if(L==NULL)return false;
 	L->next=NULL;
 	return true;
 } 
 
 /**
 	判断单链表是否为空 
 */
 bool Empty(LinkList &L){
 	if(L->next==NULL){
 		printf("链表为空\n"); 
 		return true;
	 }
	 else{
	 	printf("链表不为空\n");
	 	return false;
	 } 
 	
 } 
 
 
 
 
 
 

Guess you like

Origin blog.csdn.net/m0_56233309/article/details/126400651