函数参数的传递问题(一级指针和二级指针)
原以为自己对指针掌握了,却还是对这个问题不太明白。请教!
程序 1:
void myMalloc(char *s) //我想在函数中分配内存,再返回
{
s=(char *) malloc(100);
}
void main()
{
char *p=NULL;
myMalloc(p); //这里的 p 实际还是 NULL,p 的值没有改变,为什么?
if(p) free(p);
}
程序 2:void myMalloc(char **s)
{
*s=(char *) malloc(100);
}
void main()
{
char *p=NULL;
myMalloc(&p); //这里的 p 可以得到正确的值了
if(p) free(p);
}
程序 3:
#include<stdio.h>
void fun(int *p)
{
int b=100;
p=&b;
}
main()
{
int a=10;
int *q;
q=&a;
printf("%d",*q);
fun(q);
printf("%d",*q);
return 0;