c malloc疑问

来源:百度知道 编辑:UC知道 时间:2024/05/29 04:45:12
#include<stdio.h>
#include<stdlib.h>

struct stu{
int num;
float score;
};
void test(struct stu *);
int main(){
struct stu * p=NULL;
test(p);
printf("pointer p's value:%x\n",p);
return 0;
}

void test(struct stu * p){
p=(struct stu *)malloc(sizeof(struct stu));
printf("pointer p's value:%x\n",p);
}
以上是源代码,执行的结果显示,p只是在test函数里面被分配了空间,出了函数空间被收回了,我的目的是给p分配存储空间,怎么办?
p是指针,那它的值在函数test里被改变了,出了函数不是还能保持那个值吗?

void test(struct stu *);
int main(){
struct stu * p=NULL;
test(&p);
printf("pointer p's value:%x\n",p);
return 0;
}

void test(struct stu * *p){
*p=(struct stu *)malloc(sizeof(struct stu));
printf("pointer p's value:%x\n",*p);
}

test里的p和主函数里的p不是同一个变量,test里的p是栈上的一个临时变量,在test函数内有效,出了test函数,其生命周期就终止,可以按照二楼的做法,用一个二级指针,或者用返回值的方法把test里的p返回

void test(struct stu *);
int main(){
struct stu * p=NULL;
p=test(&p);
printf("pointer p's value:%x\n",p);
return 0;
}

struct * test(struct stu *p){
p=(struct stu *)malloc(sizeof(struct stu));
printf("pointer p's value:%x\n",p);
return p;

}
另外用malloc申请了动态内存后,应该在程序结束前释放free(p);否则有可能造成内存泄漏

保持是因为那块内存还没有被其他程序重写掉,如果这么用,迟早会出问题的
可以把p设成静态的或者干脆全局变量

p虽说是一个指针,但实质上也是一个变量,p指向的内容可以在test中改变,但是p本身的值不可以,如果是传入指向指针的指针,就可以在t