C language pointer [a very easy to make mistakes pointer parameter transfer problem]

When writing a balanced binary tree today, I encountered a problem about pointers. Let's discuss the problem first, and then rewrite the AVL tree.

Error-prone point: Don't think that the passed parameter is a pointer, it must be passed by address!

Give a classic example:

Exchange function

void mySwap02(int* a, int* b) {
	int temp = *a;
	*a = *b;
	*b = temp;
}

Here, if we want to pass parameters by address to a and b, we need to write the formal parameters in the form of pointers.

Because this can manipulate the original space, otherwise it will always be a copy of the original value.

However-it is not that you pass the pointer parameter, you can change the original value.

Look at the following case:

int* givP()
{
	int* p = (int*)malloc(sizeof(int*));
	return p;
}

void changeP(int* p)
{
	int* p2 = (int*)malloc(sizeof(int*));
	p = p2;
}

int main()
{
	int* ret = givP();
	printf("%p ", ret);
	changeP(ret);
	printf("%p ", ret);
	free(ret);
	return 0;
}

I wrote a function givP first, and allocated a block of address to ret.

Then I wrote a function. The parameter accepted by this function is also a pointer. In the body of the function, we created a new address and assigned it to p.

Print the value of ret twice:

The answer is no change.

why? Because this pointer is not the other pointer.

The original pointer points to a number,

And the pointer here becomes a parameter, its own type is a pointer,

So if we want to change it, we need to use a secondary pointer to store it.

Write it like this:

int* givP()
{
	int* p = (int*)malloc(sizeof(int*));
	return p;
}

void changeP(int** p)
{
	int* p2 = (int*)malloc(sizeof(int*));
	*p = p2;
}

int main()
{
	int* ret = givP();
	printf("%p ", ret);
	changeP(&ret);
	printf("%p ", ret);
	free(ret);
	return 0;
}

Look again:

The address was successfully changed.

Therefore, when writing code in the future, you must pay attention to finding the ontology. It cannot be because the body we found is a pointer, and the pointer is also passed by the parameter. Instead, the secondary pointer should be passed, because the pointer at this time is an ontology.

Guess you like

Origin blog.csdn.net/Kukeoo/article/details/114297006