malloc分配内存不匹配,无法输出超过3个字节的字符串

#pragma once
#include<stdio.h>
#include<string.h>
typedef struct _hero
{
	int id;
	char * name;	
}hero;
void inputhero();


#include<stdio.h>
#include<string.h>
#include"hero.h"
void inputhero()
{
	int i;	
	for (i = 0;i < 1;i++)
	{
		printf("请输入第%d位英雄的信息:\n",i+1);
		heros[i].id = i + 1;
		printf("名称:");
		heros[i].name = (char*)malloc(20);
		scanf_s("%s", heros[i].name, sizeof(heros[i].name));
		printf("名称:%s\n", heros[i].name);
     }

 

.c少了一段hero heros[5];和最后的大括号

scanf_s("%s", heros[i].name, sizeof(heros[i].name));出错。sizeof(heros[i].name)限制了字符串大小,修改大小即可

 

你输出下sizeof(heros[i].name)这个大小是不是你想象中的20?然后你就知道为什么只能输入三个字符了。

heros[i].name的类型是char*,其大小只有4个字节。