关于函数按值传递

先看一个例子:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void get_memory(char *p)
{
	p = (char *)malloc(16);
}

int main(void)
{
	char *p = NULL;
	
	get_memory(p);
	printf("%p\n", p);
	
	return 0;
}

p仍然为NULL,why?因为c中函数调用时是按值传递的,所以传递给get_memory函数的值p本身就为NULL,那么又如何能够修改p的值呢。
注意我们这里是要修改p的值,如果改成修改p所指向的内存,那是可以的,例如:

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

void set_value(char *p)
{
	*p = 'A';
}

int main(void)
{
	char *p = (char *)malloc(16);
	
	memset(p, 0, 16);
	set_value(p);
	putchar(*p);
	free(p);
	
	return 0;
}
那么前面的功能如何实现呢?有两种方式,一种是使用返回值的方式,例如:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *get_memory(void)
{
	char *p = (char *)malloc(16);
	
	return p;
}

int main(void)
{
	char *p = get_memory();
	strcpy(p, "hello world!");
	puts(p);
	free(p);
	
	return 0;
}
另外一种方式就是通过指针的方式,例如:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void get_memory(char **p)
{
	*p = (char *)malloc(16);
}

int main(void)
{
	char *p;
	
	get_memory(&p);
	strcpy(p, "hello world!");
	puts(p);
	free(p);
	
	return 0;
}
这里并不违背值传递这条规则,只是这里将p的地址传递给了函数get_memory,在get_memory函数中,通过这个地址间接的修改了p的值。

这里给我们提供了一个思路,就是在函数调用中,如果要修改参数本身的值,那么一定要使用它的地址来间接的修改其值。

你可能感兴趣的:(关于函数按值传递)