【发布时间】:2016-06-19 07:56:50
【问题描述】:
将 malloc() 的返回值分配给函数参数,然后访问该函数的外部...这里有什么问题?我的示例代码:
#include <stdio.h>
#include <stdlib.h>
struct student{
double cgpa;
int id;
char name[100];
};
void init(student *ptr)
{
ptr = (struct student*)malloc(sizeof(struct student));
ptr->id = 1;
ptr->cgpa = 4.00;
sprintf(ptr->name,"murad");
printf("In Initfunc:\nname %s\nid %d\ncgpa %lf\n",ptr->name,ptr->id,ptr->cgpa);
}
int main()
{
struct student *murad;
init(murad);
printf("IN Main:\nname %s\nid %d\ncgpa %lf\n",murad->name,murad->id,murad->cgpa);
free(murad);
return 0;
}
【问题讨论】:
-
OT:顺便说一句,如果您使用 C 编译器编译它,只需删除 malloc 结果的无用转换。
-
这个
void init(student *ptr)不是有效的 C。如果它编译,您似乎正在使用 C++ 编译器进行编译。
标签: c++ c segmentation-fault malloc