内存泄露——结构体成员指针未初始化

struct student

{

char * name;

        int  score;

}stu, *pstu;

int main()

{

strcpy(stu.name, 'Jimy');

        stu.score = 90;

        return  0;

}


问:这段代码有什么错误?

答:定义的结构体变量stu,分配了char *类型的指针指针变量name本身只分配了4个字节)和int类型的变量score;而nam指针并没有指向一个合法的地址。

正确的做法是:为name指针变量malloc一块空间。

int main()

{

stu.name = (char *) malloc(8);

strcpy(stu.name, 'Jimy');

        stu.score = 90;

        return  0;

}

唉唉唉唉,作者写错了,

#include<stdio.h>
#include <stdlib.h>
#include <string>
 struct student{
char * name;
int  score;
struct student* next;
}stu,*stu1;

int main()

{
//stu.name = (char*) malloc(sizeof(char));
    stu.name = (char*)malloc(sizeof(char)); //*1.结构体成员指针需要初始化*/  
strcpy(stu.name, 'Jimy');
stu.score = 90;
return  0;
}

报错:error C2664: “strcpy”: 不能将参数 2 从“int”转换为“const char *”

1>        从整型转换为指针类型要求 reinterpret_cast、C 样式转换或函数样式转换


原来“”作者写成'',aiiaia唉唉i啊

猜你喜欢

转载自blog.csdn.net/hk121/article/details/80840602