求懂的人解释一下,谢谢
代码意思是想在传结构体指针给函数,在函数里面改变结构体各项的值,运行结果为:a和b的值能改变,但到打印指针c的时候,程序报错
#include
struct stu
{
int a;
int b;
char *c;
};
//给结构体s1初始化
void Fun(void *ptr)
{
char *s = (char *)malloc(10);
s = "Hello World";
int *p = (int *)ptr;
*p = 100; //value of a
*(p+1) = 101; //value of b
*(p+2) = s; //value of c,c is a pointer
}
int main()
{
struct stu s1;
Fun(&s1);
printf("s1.a value = %d \n",s1.a);
printf("s1.b value = %d \n",s1.b);
printf("s1.c value = %s \n",s1.c);
return 0;
}
void Fun(void *ptr)传过去的值得类型应该是结构体指针表吧?void Fun(struct stu *ptr)
Fun函数内部应该:
p+=2;
p=s;
因为p和s都为指针.
这程序看着有点乱,而且有内存泄露的问题
void Fun(void *ptr)
{
struct stu *p = ptr;
if (NULL != p) {
p->a = 100;
p->b = 101;
p->c = (char*)malloc(15);
memcpy(p->c, "Hello world", 12);
}
}
想办法避免内存泄露吧