大家都知道,指针变量存储的地址,但是,在进行函数调用的时候,大家有想过能否将指针变量本身传递给一个函数了?
这里首先给大家纠正一个错误,其实main函数内部声明的变量也是局部变量,它们也只是在main函数内部有效,只不过是它们的生命周期和全局变量一样长而已。全局变量一定是定义在函数外部的。
好了,现在大家知道了--------无法把指针变量本身传递给一个函数。测试一下:
#include <stdlib.h>
#include <stdlib.h>
#include <string.h>
void allocate_mem(char *p, int n)
{
p = (char *)malloc(n * sizeof(char));
}
int main(void)
{
char *dst = NULL;
allocate_mem(dst, 20);
strcpy(dst, "I love Linux");
free(dst);
return 0;
}经测试,单步调试执行到strcpy函数时出现:No source available for "memcpy() at 0x5263f46" (以上测试在Fedora9 eclipse环境下)。观察得到dst的值仍然为NULL,说明malloc函数动态分配的内存没有赋给dst,而是赋给了dst一个备份,而这个备份是随编译器自动分配和回收的,当allocate_mem函数调用结束,这个备份也就被释放。
那么怎样获得一块内存区了?
1、用指针函数实现
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char *allocate_mem(char *p, int n)
{
p = (char *)malloc(n * sizeof(char));
return p;
}
int main(void)
{
char *dst = NULL;
dst = allocate_mem(dst, 20);
strcpy(dst, "I love Linux");
free(dst);
return 0;
}2、用二级指针实现
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
void allocate_mem(char **p, int n)
{
*p = (char *)malloc(n * sizeof(char));
}
int main(void)
{
char *dst = NULL;
allocate_mem(&dst, 20);
strcpy(dst, "I love Linux");
free(dst);
return 0;
}这里很显然,参数是&dst,而不是dst指针变量,这样传递是地址,而非dst变量本身。
本文探讨了如何正确地使用指针来分配内存。通过对比不同的方法,解释了为什么直接传递指针变量无法达到预期效果,并提供了两种有效的解决方案:使用指针函数返回分配的内存地址或利用二级指针。
704

被折叠的 条评论
为什么被折叠?



