结构指针的坑之(定义结构体指针时并没有分配存储空间,所以要用malloc()申请空间)

这段代码会报错,核心转储
#include<stdio.h>
#include <string.h>

struct role   // 定义一个结构体
{
//    char name[100];  // 姓名
    int level;  // 等级
    int HP;  // 血量
    int MP;  // 蓝量
    int gold;  // 金币
};

int main()
{
    //struct role p;   // 定义一个结构体指针
    //struct role *w=NULL;
    //w=&p;
    //
    struct role *w;
    char str[]="kuangzhan";

  //  strcpy(w->name,"tom");
    //w->name = "teslaaa";     // 对结构体中的成员变量name进行赋值
    w->level = 46;  // 对结构体中的成员变量level进行赋值
    w->HP = 3100;       // 对结构体中的成员变量HP进行赋值
    w->MP = 3100;       // 对结构体中的成员变量MP进行赋值
    w->gold = 475233;       // 对结构体中的成员变量gold进行赋值

    printf("%d\n%d\n",w->HP,w->MP);
   return 0;
}

定义结构体指针时并没有分配存储空间
解决方案
  1. 用malloc()申请空间
 struct role *w;
 w = (struct role*)malloc(sizeof(struct role));
  1. 用new 直接分配空间 role *w= new role;
  2. 定义一个struct,在把变量名字赋值
    struct role p;   // 定义一个结构体指针
    struct role *w=NULL;
    w=&p;
#include<stdio.h>
#include <string.h>
#include <stdlib.h>
struct role   // 定义一个结构体
{
    char name[100];  // 姓名
    int level;  // 等级
    int HP;  // 血量
    int MP;  // 蓝量
    int gold;  // 金币
};

int main()
{
    /*一种简单的写法 定义一个结构体,将他的的名字付给同型的结构体指针
     *
    struct role p;   // 定义一个结构体指针
    struct role *w=NULL;
    w=&p;
    */

    /* 用malloc ,来分配内存空间
     *
    struct role *w;
    w = (struct role*)malloc(sizeof(struct role));
    */


    //char str[]="kuangzhan";

    role *w= new role;
    strcpy(w->name,"tom");
    //w->name = "teslaaa";     // 对结构体中的成员变量name进行赋值
    w->level = 46;  // 对结构体中的成员变量level进行赋值
    w->HP = 3100;       // 对结构体中的成员变量HP进行赋值
    w->MP = 8100;       // 对结构体中的成员变量MP进行赋值
    w->gold = 475233;       // 对结构体中的成员变量gold进行赋值

    printf("%s的血量是%d\n 蓝量是%d\n 金币的数量%d",w->name,w->HP,w->MP,w->gold);
    //printf("s的血量是%d\n 蓝量是%d\n 金币的数量%d",w->HP,w->MP,w->gold);

   return 0;
}
posted @ 2022-08-19 22:46  luoganttcc  阅读(32)  评论(0)    收藏  举报