结构体内存分配
#include <stdio.h>#include <string.h>
#include <stdlib.h>
#pragma warning(disable:4996)
struct teacher
{
int age;
char *name;
};
int createTeacher(struct teacher **p1,int num)
{
struct teacher *temp_p = NULL;
int i = 0;
if (p1 == NULL)
{
fprintf(stderr, "err\n");
return -1;
}
temp_p = (struct teacher*)malloc(sizeof(struct teacher)*num);
if (temp_p = NULL)
{
fprintf(stderr, "err1\n");
return -1;
}
memset(temp_p, 0, sizeof(struct teacher)*num);
for (i = 0; i < num; i++)
{
temp_p.name = (char*)malloc(sizeof(char)*64);
if (temp_p.name = NULL)
{
fprintf(stderr, "err2\n");
return -1;
}
memset(temp_p.name, 0, sizeof(char) * 64);
}
*p1 = temp_p;
return 0;
}
void print_teacher(struct teacher *p,int num)
{
int i = 0;
for (i = 0; i < num; i++)
{
printf("name:%s\n", p.name);
printf("age:&d\n", p.age);
}
}
int main()
{
struct teacher *p = NULL;
int num = 3;
int ret = 0;
int i = 0;
ret = createTeacher(&p, num);
if (ret < 0)
{
fprintf(stderr,"err3\n");
return -1;
}
for (i = 0; i < num; i++)
{
printf("请输入第%d个老师姓名:",i+1);
scanf("%s", p.name);
printf("请输入第%d个老师年龄:",i+1);
scanf("%d",&(p.age));
}
print_teacher(p, num);
return 0;
}
初学者,编译时总会提示0x50114025 (msvcr120d.dll) (结构体嵌套.exe 中)处有未经处理的异常:0xC0000005:写入位置 0x00000000 时发生访问冲突,求指教~~~~ 自己已解决,纯属粗心所致~
页:
[1]